Leetcode Binary Tree Preorder, inorder, postorder Traversal
- 题目
- 解析:
题目
https://leetcode.com/problems/binary-tree-preorder-traversal/
https://leetcode.com/problems/binary-tree-inorder-traversal/submissions/
https://leetcode.com/problems/binary-tree-postorder-traversal/submissions/
解析:
一律用dfs来写,只需要改变访问节点的位置即可
preorder
class Solution:def postorderTraversal(self, root: TreeNode) -> List[int]:def dfs(node):if not node:returndfs(node.left)dfs(node.right)ans.append(node.val)ans = []dfs(root)return ans
inorder
class Solution:def inorderTraversal(self, root: TreeNode) -> List[int]:def dfs(node):if not node:returndfs(node.left)ans.append(node.val)dfs(node.right)ans = []dfs(root)return ans
postorder
class Solution:def postorderTraversal(self, root: TreeNode) -> List[int]:def dfs(node):if not node:returndfs(node.left)dfs(node.right)ans.append(node.val)ans = []dfs(root)return ans