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 preorder_elements(t): """生成器遍历""" s = SStack() while t is not None or not s.is_empty(): while t is not None: s.push(t.right) yield t.data t = t.left t = s.pop()
def preorder_nonrec(t, proc): """先序循环法""" s = SStack() while t is not None or not s.is_empty(): while t is not None: # 沿左分支下行 proc(t.data) # 先根序先处理根数据 s.push(t.right) # 右分支如栈 t = t.left t = s.pop() # 遇到空树,回溯
def DFS_graph(graph, v0): """"深度优先的非递归算法""" vnum = graph.vertex_num() visited = [0] * vnum visited[v0] = 1 DFS_seq = [v0] st = SStack() st.push((0, graph.out_edges(v0))) while not st.is_empty(): i, edges = st.pop() if i < len(edges): v, e = edges[i] # pylint: disable=unused-variable st.push((i + 1, edges)) if not visited[v]: DFS_seq.append(v) visited[v] = 1 st.push((0, graph.out_edges(v))) return DFS_seq