classSolution: defpreorderTraversal(self, root: TreeNode) -> List[int]: defdfs(root): ifnot root: return res.append(root.val) dfs(root.left) dfs(root.right) res = list() dfs(root) return res
一路向左,没有才右~
栈用来存放每次遍历到的节点,为后续探索留退路(栈里面的节点是后续探索节点的祖先);
一旦“祖先”出场指引前往右子树的方向,祖先就得出栈(小祖先帮不了忙,再请大祖先出场)。
classSolution: defpreorderTraversal(self, root: TreeNode) -> List[int]: res = list() ifnot root: return node = root stack = list() while node: res.append(node.val) stack.append(node) node = node.left whilenot node and stack: node = stack.pop() node = node.right return res
这个方法有中序线索二叉树的味道,利用线索实现回到父节点的能力。
classSolution: defpreorderTraversal(self, root: TreeNode) -> List[int]: res = list() ifnot root: return res p = root while p: ifnot p.left: res.append(p.val) p = p.right else: pre = p.left while pre.right and pre.right != p: pre = pre.right ifnot pre.right: pre.right = p res.append(p.val) p = p.left else: pre.right = None p = p.right return res
中序遍历
[x] 94:Binary Tree Inorder Traversal
classSolution: definorderTraversal(self, root: TreeNode) -> List[int]: defdfs(root): ifnot root: return dfs(root.left) res.append(root.val) dfs(root.right) res = list() dfs(root) return res
一路向左,没有才右~
跟迭代法前序遍历的区别在于访问节点的顺序不同。
classSolution: definorderTraversal(self, root: TreeNode) -> List[int]: res = list() ifnot root: return res node = root stack = list() while node: stack.append(node) node = node.left whilenot node and stack: node = stack.pop() res.append(node.val) node = node.right return res
跟Morris法前序遍历的区别在于访问节点的顺序不同。
classSolution: definorderTraversal(self, root: TreeNode) -> List[int]: res = list() ifnot root: return res p = root while p: ifnot p.left: res.append(p.val) p = p.right else: pre = p.left while pre.right and pre.right != p: pre = pre.right ifnot pre.right: pre.right = p p = p.left else: pre.right = None res.append(p.val) p = p.right return res
后序遍历
[x] 145:Binary Tree Postorder Traversal
classSolution: defpostorderTraversal(self, root: TreeNode) -> List[int]: defdfs(root): ifnot root: return root dfs(root.left) dfs(root.right) res.append(root.val) res = list() dfs(root) return res