vlambda博客
学习文章列表

二叉树的4种遍历方式

1、前序遍历

    def printTree(self, t: TreeNode): if t is not None: print(t.val, ' ') self.printTree(t.left) self.printTree(t.right)

2、中序遍历

    def printTree(self, t: TreeNode): if t is not None: self.printTree(t.left)            print(t.val, ' ') self.printTree(t.right)

3、后续遍历

 def printTree(self, t: TreeNode): if t is not None:            self.printTree(t.left) self.printTree(t.right) print(t.val, ' ')

4、层次遍历

def levelOrder(root: TreeNode) -> list: if root is None: return []
res= [] queue = [root] while queue: temp = [] res_t = [] for node in queue: res_t.append(node.val) if node.left: temp.append(node.left) if node.right: temp.append(node.right) queue = temp res.append(res_t)
return res