Binary tree pre-order, mid-order, post-order, sequence traversal (recursion, iteration, stack, queue)
1. Preorder traversal of binary tree
1.1 Topic description
Difficulty: Moderate
1.2 Problem analysis
This problem is the basic problem of binary tree related problems. The use of recursion is a relatively easy way to think of, but advanced problems require iterative algorithms to complete. This needs to be thought about. But regarding the pre-order, middle-order and post-order traversal of the binary tree, there is a unified template that can be applied . Let's take a look at what this template is:
"""
二叉树遍历模板
采用栈的方法
"""
stack = []
cur = root
while stack or cur:
if cur:
pass
else:
pass
The pre-order, middle-order and post-order traversal of the binary tree can be implemented using the above-mentioned stack template, and only need to modify the pass segment in the code according to the situation. The order of the preorder traversal of the binary tree is the root node-> left subtree-> right subtree . Let's see how the preorder traversal of the binary tree is implemented.
1.3 Python implementation
- Recursion
First, use the recursive method to achieve:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)
The running result is:
- Iteration (stack)
uses the above template to achieve:
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
stack = []
res = []
cur = root
while stack or cur:
if cur:
stack.append(cur)
res.append(cur.val)
cur = cur.left
else:
cur = stack.pop()
cur = cur.right
return res
The running result is:
2. Mid-order traversal of binary tree
2.1 Topic description
Difficulty: Moderate
2.2 Problem analysis
The middle-order traversal is similar to the previous-order traversal. The traversal order is left subtree-> root node-> right subtree . There are two ways to implement recursion and iteration. Iteration is realized using the template in section 1.2.
2.3 Python implementation
- Recursive implementation
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)
The output is:
- Iterative implementation (stack)
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
stack = []
res = []
cur = root
while stack or cur:
if cur:
stack.append(cur)
cur = cur.left
else:
cur = stack.pop()
res.append(cur.val)
cur = cur.right
return res
The output is:
3. Postorder traversal of binary tree
2.1 Topic description
Difficulty: difficult
2.2 Problem analysis
Postorder sequence is left subtree -> right subtree -> root node , and the preamble sequence preorder, inorder traversal similar, iterative and recursive manner to achieve two kinds of iteration using the template 1.2 Achieved.
2.3 Python implementation
- Recursive implementation
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
return self.postorderTraversal(root.left) + self.postorderTraversal(root.right) + [root.val]
The running result is:
- Iterative implementation (stack)
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
stack = []
res = []
cur = root
temp = None
while stack or cur:
if cur:
stack.append(cur)
cur = cur.left
else:
cur = stack[-1]
if(cur.right is None or cur.right == temp):
res.append(cur.val)
temp = cur
stack.pop()
cur = None
else:
cur = cur.right
return res
The running result is:
4. Sequence traversal of binary tree
2.1 Topic description
Difficulty: Moderate
2.2 Problem analysis
The traversal order of the sequence traversal is: first layer: root node, second layer: left node, right node, third layer ... The output is a two-dimensional list. Different from the first three questions, sequence traversal cannot be realized by stack structure, but by queue. Proceed as follows:
- Put the root node in the queue
- Take the node in the queue, add its value to the output, and put the left and right children of the node in the queue
- Take the length of the queue as the number of cycles, take the first value of the column of the queue in sequence, add the value of the node to the output result, and put the left and right child nodes of the node into the queue
- Repeat the third step until the queue is empty
2.3 Python implementation
code show as below:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# 队列
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
res = []
queue = [root]
temp = []
while queue:
lens = len(queue)
temp = []
while lens:
cur = queue[0]
del queue[0]
temp.append(cur.val)
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
lens -= 1
res.append(temp)
return res
The output is: