二叉树先序、中序、后序遍历 递归与非递归 Python实现

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)
 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.按层遍历:从上到下、从左到右按层遍历

 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.二叉树节点个数

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.二叉树的最大深度

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)
posted @ 2018-06-02 23:51  icekx  阅读(15841)  评论(3编辑  收藏  举报