前序:
1 class Solution: 2 def preorderTraversal(self, root: TreeNode) -> List[int]: 3 res=[] 4 stack=[] 5 while root or stack: 6 if root: 7 stack.append(root) 8 res.append(root.val) 9 root=root.left 10 else: 11 root=stack.pop() 12 root=root.right 13 return res
后序:
1 class Solution: 2 def postorderTraversal(self, root: TreeNode) -> List[int]: 3 stack=[] 4 res=[] 5 while root or stack: 6 if root: 7 stack.append(root) 8 res.append(root.val) 9 root=root.right 10 else: 11 root=stack.pop() 12 root=root.left 13 return res[::-1]
中序:
1 class Solution: 2 def inorderTraversal(self, root: TreeNode) -> List[int]: 3 stack=[] 4 res=[] 5 while stack or root: 6 if root: 7 stack.append(root) 8 root=root.left 9 else: 10 root = stack.pop() 11 res.append(root.val) 12 root=root.right 13 return res
2019-12-27 21:56:55