二叉樹先序、中序、後序遍歷 遞歸與非遞歸 Python實現

1.先序遍歷:根節點->左子樹->右子樹node

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.中序遍歷:左子樹->根節點->右子樹app

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.後序遍歷:左子樹->右子樹->根節點post

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)
 1 # 後序打印二叉樹(非遞歸)
 2 # 使用兩個棧結構
 3 # 第一個棧進棧順序:左節點->右節點->跟節點
 4 # 第一個棧彈出順序: 跟節點->右節點->左節點(先序遍歷棧彈出順序:跟->左->右)
 5 # 第二個棧存儲爲第一個棧的每一個彈出依次進棧
 6 # 最後第二個棧依次出棧
 7 def postOrderTraverse(node):
 8     stack = [node]
 9     stack2 = []
10     while len(stack) > 0:
11         node = stack.pop()
12         stack2.append(node)
13         if node.left is not None:
14             stack.append(node.left)
15         if node.right is not None:
16             stack.append(node.right)
17     while len(stack2) > 0:
18         print(stack2.pop().val)

 

4.按層遍歷:從上到下、從左到右按層遍歷spa

 1 # 先進先出選用隊列結構
 2 import queue
 3 def layerTraverse(head):
 4     if not head:
 5         return None
 6     que = queue.Queue()      # 建立先進先出隊列
 7     que.put(head)
 8     while not que.empty():
 9         head = que.get()    # 彈出第一個元素並打印
10         print(head.val)
11         if head.left:       # 若該節點存在左子節點,則加入隊列(先push左節點)
12             que.put(head.left)
13         if head.right:      # 若該節點存在右子節點,則加入隊列(再push右節點)
14             que.put(head.right)

 

5.二叉樹節點個數code

1 # 求二叉樹節點個數
2 def treeNodenums(node):
3     if node is None:
4         return 0
5     nums = treeNodenums(node.left)
6     nums += treeNodenums(node.right)
7     return nums + 1

 

6.二叉樹的最大深度blog

1 # 二叉樹的最大深度
2 def bTreeDepth(node):
3     if node is None:
4         return 0
5     ldepth = bTreeDepth(node.left)
6     rdepth = bTreeDepth(node.right)
7     return (max(ldepth, rdepth) + 1)
相關文章
相關標籤/搜索