非递归遍历二叉树的方法 发表于 2019-04-03 | 分类于 算法 | | 前言统一的简洁的二叉树非递归遍历写法 先序遍历1234567891011121314151617def preOrder(root,path): s = [] if not root: return s s.push([root,False]) while not s: node, visited = s[-1] s.pop() if not node: continue if visited: path.append(node) else: s.append([node.right,False]) s.append([node.left,False]) s.append([node,True]) return path 中序遍历1234567891011121314151617def inOrder(root,path): s = [] if not root: return s s.push([root,False]) while not s: node, visited = s[-1] s.pop() if not node: continue if visited: path.append(node) else: s.append([node.right,False]) s.append([node,True]) s.append([node.left,False]) return path 后序遍历1234567891011121314151617def postOrder(root,path): s = [] if not root: return s s.push([root,False]) while not s: node, visited = s[-1] s.pop() if not node: continue if visited: path.append(node) else: s.append([node,True]) s.append([node.right,False]) s.append([node.left,False]) return path