tree.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. from typing import Optional
  2. class TreeNode:
  3. def __init__(self, val=0, left=None, right=None):
  4. self.val = val
  5. self.left = left
  6. self.right = right
  7. class Solution:
  8. # 中序遍历
  9. def inorderTraversal(self, root: Optional[TreeNode]):
  10. if root == None:
  11. return []
  12. left = self.inorderTraversal(root.left)
  13. right = self.inorderTraversal(root.right)
  14. return left + [root.val] + right
  15. # 先序遍历
  16. def preorderTraversal(self, root: Optional[TreeNode]):
  17. if root == None:
  18. return []
  19. left = self.preorderTraversal(root.left)
  20. right = self.preorderTraversal(root.right)
  21. return [root.val] + left + right
  22. # 后序遍历
  23. def postorderTraversal(self, root: Optional[TreeNode]):
  24. if root == None:
  25. return []
  26. left = self.postorderTraversal(root.left)
  27. right = self.postorderTraversal(root.right)
  28. return left + right + [root.val]
  29. # 回溯通用模板
  30. # res = []
  31. #
  32. # def backtrack(路径, 选择列表):
  33. # if 满足结束条件:
  34. # res.append(路径)
  35. # return
  36. #
  37. # if 满足剪枝条件: return
  38. #
  39. # for 选择 in 选择列表:
  40. # 做选择
  41. # backtrack(路径, 选择列表)
  42. # 撤销选择