0%
迭代法
Leetcode相关题目:94,144,145
前序遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: result = [] st= [] if root: st.append(root) while st: node = st.pop() if node != None: if node.right: st.append(node.right) if node.left: st.append(node.left) st.append(node) st.append(None) else: node = st.pop() result.append(node.val) return result
|
中序遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: result = [] st = [] if root: st.append(root) while st: node = st.pop() if node != None: if node.right: st.append(node.right) st.append(node) st.append(None) if node.left: st.append(node.left) else: node = st.pop() result.append(node.val) return result
|
后序遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: result = [] st = [] if root: st.append(root) while st: node = st.pop() if node != None: st.append(node) st.append(None) if node.right: st.append(node.right) if node.left: st.append(node.left) else: node = st.pop() result.append(node.val) return result
|
递归法
前序遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: result = [] def traversal(root: TreeNode): if root == None: return result.append(root.val) traversal(root.left) traversal(root.right)
traversal(root) return result
|
中序遍历
1 2 3 4 5 6 7 8 9 10 11 12 13
| class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: result = []
def traversal(root: TreeNode): if root == None: return traversal(root.left) result.append(root.val) traversal(root.right)
traversal(root) return result
|
后序遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: result = []
def traversal(root: TreeNode): if root == None: return traversal(root.left) traversal(root.right) result.append(root.val)
traversal(root) return result
|