def trans_infix_suffix(line): st = SStack() exp = [] for x in tokens(line): # tokens是一个待定义的生成器 if x not in infix_operators: # 运算对象直接送出 exp.append(x) elif st.is_empty() or x == '(': # 左括号进栈 st.push(x) elif x == ')': # 处理右括号的分支 while not st.is_empty() and st.top() != '(': exp.append(st.pop()) if st.is_empty(): # 没有找到左括号,就是不配对 raise SyntaxError('Missing "(".') st.pop() # 弹出左括号,右括号也不进栈 else: # 处理运算符,运算符都看作左结合 while (not st.is_empty()) and priority[st.top()] >= priority[x]: exp.append(st.pop()) st.push(x) # 算数运算符进栈 while not st.is_empty(): # 送出栈里剩下的运算符 if st.pop() == '(': # 如果还有左括号,就是不配对 raise SyntaxError('Extra "(".') exp.append(st.pop()) return exp
def postorder_nonrec(t_, proc): s = SStack() while t_ is not None or not s.is_empty(): while t_ is not None: # 下行循环,直到栈顶的两个树空 s.push(t_) t_ = t_.left if t_.left is not None else t_.right # 注意这个条件表达式的意义:能左就左,否则向右一步 t_ = s.pop() # 栈顶是访问结点 proc(t_.dat) if not s.is_empty() and s.top().left == t_: t_ = s.top().right # 栈不空且当前结点是栈顶的左子结点 else: t_ = None # 没有右子树或右子树遍历完毕,强迫退栈
def postorder_nonrec(t, proc): s = SStack() while t is not None or not s.is_empty(): while t is not None: #下行循环,直到栈顶的两子树空 s.push(t) t = t.left if t.left is not None else t.right #能左就左否则向右 t = s.pop() #栈顶是应访问节点 proc(t.data) if not s.is_empty() and s.top().left == t: t = s.top().right #栈不空且当前节点是栈定左子节点 else: #没有右子树或右子树遍历完毕,强迫退栈 t = None
def dfs_non_recursive_traverse_postorder(t, proc): #dfs非递归 后根序 s = SStack() while t is not None or not s.is_empty(): while t is not None: s.push(t) if t.left is not None: t = t.left else: t = t.right t = s.pop() proc(t.data) if not s.is_empty() and s.top().left == t: t = s.top().right #这一步很关键 else: t = None