二叉树遍历

二叉树节点的定义

  1. # simple版本,自己常用
  2. class TreeNode:
  3. def __init__(self, x):
  4. self.val = x
  5. self.left = None
  6. self.right = None
  7. # leetcode版本
  8. class TreeNode:
  9. def __init__(self, val=0, left=None, right=None):
  10. self.val = val
  11. self.left = left
  12. self.right = right

构建二叉树

  1. def create_binary_tree(input_list=[]):
  2. if input_list is None or len(input_list)==0:
  3. return None
  4. data = input_list.pop(0)
  5. if data is None:
  6. return None
  7. node = TreeNode(data)
  8. node.left = create_binary_tree(input_list)
  9. node.right = create_binary_tree(input_list)
  10. return node

深度优先遍历

144. 二叉树的前序遍历
94. 二叉树的中序遍历
145. 二叉树的后序遍历

  1. # 前序遍历
  2. def preorder(root):
  3. if root is None:
  4. return
  5. print(root.val) # 根
  6. preorder(root.left) # 左
  7. preorder(root.right) # 右
  8. return root
  9. # 中序遍历
  10. def inorder(root):
  11. if root is None:
  12. return
  13. inorder(root.left) # 左
  14. print(root.val) # 根
  15. inorder(root.right) # 右
  16. return root
  17. # 后序遍历
  18. def postorder(root):
  19. if root is None:
  20. return
  21. postorder(root.left) # 左
  22. postorder(root.right) # 右
  23. print(root.val) # 根
  24. return root

广度优先遍历

102. 二叉树的层序遍历

  1. # 层序遍历
  2. from queue import Queue
  3. def levelOrder(root):
  4. if not root:
  5. return []
  6. queue = Queue()
  7. queue.put(root)
  8. ans = []
  9. while not queue.empty():
  10. tmp = []
  11. n = queue.qsize()
  12. for _ in range(n):
  13. root = queue.get()
  14. tmp.append(root.val)
  15. if root.left:
  16. queue.put(root.left)
  17. if root.right:
  18. queue.put(root.right)
  19. ans.append(tmp)
  20. return ans

107. 二叉树的层序遍历 II

N叉树遍历

N叉树节点的定义

  1. class Node:
  2. def __init__(self, val=None, children=None):
  3. self.val = val
  4. self.children = children

深度优先遍历

589. N 叉树的前序遍历
590. N 叉树的后序遍历

  1. # 前序遍历
  2. def preorder(root):
  3. if root is None:
  4. return
  5. print(root.val) # 父
  6. for node in root.children: # 子
  7. preorder(node)
  8. return root
  9. # 后序遍历
  10. def postorder(root):
  11. if root is None:
  12. return
  13. for node in root.children: # 子
  14. postorder(node)
  15. print(root.val) # 父
  16. return root

广度优先遍历

429. N 叉树的层序遍历

  1. # 层序遍历
  2. from queue import Queue
  3. def levelOrder(root):
  4. if not root:
  5. return []
  6. queue = Queue()
  7. queue.put(root)
  8. ans = []
  9. while not queue.empty():
  10. tmp = []
  11. n = queue.qsize()
  12. for _ in range(n):
  13. root = queue.get()
  14. tmp.append(root.val)
  15. for node in root.children:
  16. queue.put(node)
  17. ans.append(tmp)
  18. return ans