二叉树的遍历(python)
一、中序
1. 递归
class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] res = [] res.extend(self.inorderTraversal(root.left)) res.append(root.val) res.extend(self.inorderTraversal(root.right)) return res
2. 迭代
class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: p = root stack = [] res = [] while p or stack: while p: stack.append(p) p = p.left p = stack.pop() res.append(p.val) p = p.right return res
3. Morris
class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: res = [] p = root while p: if p.left: predecessor = p.left while predecessor.right: predecessor = predecessor.right predecessor.right = p temp = p p = p.left temp.left = None else: res.append(p.val) p= p.right return res
二、前序
1. 递归
class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] res = [root.val] res.extend(self.inorderTraversal(root.left)) res.extend(self.inorderTraversal(root.right)) return res
2. 迭代
class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: res = [] stack = [] p = root while stack or p: while p: res.append(p.val) stack.append(p.right) p = p.left p = stack.pop() return res
3. Morris
class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: res = list() p1 = root while p1: p2 = p1.left if p2: while p2.right and p2.right != p1: p2 = p2.right if not p2.right: res.append(p1.val) p2.right = p1 p1 = p1.left continue else: p2.right = None else: res.append(p1.val) p1 = p1.right return res
三、后序
1. 递归
class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] res = [] res.extend(self.inorderTraversal(root.left)) res.extend(self.inorderTraversal(root.right)) res.append(root.val) return res
2. 迭代
class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: res = [] stack = [] prev = None p = root while p or stack: while p: stack.append(p) p= p.left p = stack.pop() if not p.right or p.right == prev: res.append(p.val) prev = p p = None else: stack.append(p) p = p.right return res
3. Morris
class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: def addPath(node: TreeNode): count = 0 while node: count += 1 res.append(node.val) node = node.right i, j = len(res) - count, len(res) - 1 while i < j: res[i], res[j] = res[j], res[i] i += 1 j -= 1 res = [] p1 = root while p1: p2 = p1.left if p2: while p2.right and p2.right != p1: p2 = p2.right if not p2.right: p2.right = p1 p1 = p1.left continue else: p2.right = None addPath(p1.left) p1 = p1.right addPath(root) return res