当前位置: 代码迷 >> 综合 >> Leetcode Binary Tree Preorder, inorder, postorder Traversal (python)
  详细解决方案

Leetcode Binary Tree Preorder, inorder, postorder Traversal (python)

热度:75   发布时间:2023-11-26 06:45:35.0

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
  相关解决方案