二叉树的遍历
1.先序遍历:根节点->左子树->右子树
1 # 先序打印二叉树(递归)
2 def preOrderTraverse(node):
3 if node is None:
4 return None
5 print(node.val)
6 preOrderTraverse(node.left)
7 preOrderTraverse(node.right)
1 # 先序打印二叉树(非递归)
2 def preOrderTravese(node):
3 stack = [node]
4 while len(stack) > 0:
5 print(node.val)
6 if node.right is not None:
7 stack.append(node.right)
8 if node.left is not None:
9 stack.append(node.left)
10 node = stack.pop()
2.中序遍历:左子树->根节点->右子树
1 # 中序打印二叉树(递归)
2 def inOrderTraverse(node):
3 if node is None:
4 return None
5 inOrderTraverse(node.left)
6 print(node.val)
7 inOrderTraverse(node.right)
1 # 中序打印二叉树(非递归)
2 def inOrderTraverse(node):
3 stack = []
4 pos = node
5 while pos is not None or len(stack) > 0:
6 if pos is not None:
7 stack.append(pos)
8 pos = pos.left
9 else:
10 pos = stack.pop()
11 print(pos.val)
12 pos = pos.right
3.后序遍历:左子树->右子树->根节点
1 # 后序打印二叉树(递归)
2 def postOrderTraverse(node):
3 if node is None:
4 return None
5 postOrderTraverse(node.left)
6 postOrderTraverse(node.right)
7 print(node.val)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
if root == None:
return []
pre = None
res = []
stack = [root]
while stack:
temp = stack[-1] # 这里不能直接用pop,因为只有读取该节点的时候才要已经读取了的节点pop出栈
if (temp.left == None and temp.right == None) or (pre and (pre == temp.left or pre == temp.right)):
# 用pre来进行标志,由于是后序遍历,
# 如果当前节点是叶节点(左右子节点为空),读取值,
# 如果不是叶节点但是pre是他的子节点,
# 就说明这个节点也是当前应该读取的点
res.append(temp.val)
pre = temp
stack.pop()
else: # 因为栈先进后出,因此子节点压入的顺序是先右后左。
if temp.right:
stack.append(temp.right)
if temp.left:
stack.append(temp.left)
return res
4.按层遍历:从上到下、从左到右按层遍历
# 先进先出选用队列结构
import queue
def layerTraverse(head):
if not head:
return None
que = queue.Queue() # 创建先进先出队列
que.put(head)
while not que.empty():
head = que.get() # 弹出第一个元素并打印
print(head.val)
if head.left: # 若该节点存在左子节点,则加入队列(先push左节点)
que.put(head.left)
if head.right: # 若该节点存在右子节点,则加入队列(再push右节点)
que.put(head.right)
参考博客:https://www.cnblogs.com/icekx/p/9127569.html