# A summary of hierarchical traversal of binary trees

• The general level traversal of binary tree is breadth first traversal (BFS), which traverses horizontally and prints out each node in the order of layers.

Therefore, we need a queue. When dealing with a node, the function first adds its left and right child nodes to the queue in order. In this way, the nodes of each layer are traversed from left to right. In order to prevent some empty trees from joining the queue and wasting storage space, it is necessary to check the existence of child nodes before operation.

## 1, Hierarchical traversal of [LeetCode 102] binary tree

#### 1. Title Description

Given a binary tree, it returns the value of the nodes it traverses hierarchically. (that is, access all nodes layer by layer, from left to right).

For example:
Given a binary tree: [3,9,20,null,null,15,7],

```    3
/ \
9  20
/  \
15   7
```

The result of the level traversal is as follows:

```[
[3],
[9,20],
[15,7]
]
```

#### 2. way of thinking

You need an array res to store the node values of each layer; you also need a queue to store the nodes of each layer. As long as the queue is not empty, you need to continue to traverse. Here you need a while loop.

• Calculate the length of each layer, that is, the number of nodes in each layer; define a list to store the node values of the current layer.
• Traverse the current layer, take out the nodes of the current layer from the queue and add the values to the list;
• Then judge whether the left and right children of the current node exist, and add them to the queue in turn.
• After traversing the nodes of the current layer, the for loop will pop out and the list will be added to res.
When the queue is empty, it indicates that the traversal is over, and the exit loop returns res to get the hierarchical traversal of each layer's results.

#### 3. code

```# 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]
while queue:
n = len(queue)
list = []
for i in range(0, n):
cur = queue.pop(0)
list.append(cur.val)
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
res.append(list)
return res
```

## 2, The level traversal of [LeetCode 107] binary tree II

#### 1. Title Description

Given a binary tree, the node value is traversed from bottom to top. (that is, from the layer where the leaf node is to the layer where the root node is, traverse from left to right layer by layer)

For example:
Given a binary tree [3,9,20,null,null,15,7],

```    3
/ \
9  20
/  \
15   7
```

The bottom-up level traversal is as follows:

```[
[15,7],
[9,20],
[3]
]
```

#### 2. way of thinking

The idea is as like as two peas in the above 102 questions, but there is a difference in the final way of adding: because we want to output from bottom to top, and we are top-down traversal, so we need to use the insert method levels.insert(0, res) to add the node value to each array, and we can get the correct result by the head interpolation method.

#### 3. code

```# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
levels = []
if not root:
return []
queue = [root]
node = root
while queue:
res = []
n = len(queue)
for i in range(0, n):
node = queue.pop(0)
res.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
levels.insert(0, res)   #The way to add is different here. It's no longer append
return levels
```

## 3, Zigzag level traversal of [LeetCode 103] binary tree

#### 1. Title Description

Given a binary tree, it returns the zigzag level traversal of its node values. (that is, first from left to right, then from right to left to traverse the next layer, and so on, alternating between layers).

For example:
Given a binary tree [3,9,20,null,null,15,7],

```    3
/ \
9  20
/  \
15   7
```

Return the zigzag level traversal as follows:

```[
[3],
[20,9],
[15,7]
]
```

#### 2. way of thinking

The idea is similar to question 102, but there is an additional level variable to determine whether the current level is in the odd or even level. If the level is in the odd level, the node value is normally added to the list res.append(node.val); if the level is in the even level, the head interpolation res.insert(0, node.val) is required. Because the problem stem requires traversing from left to right, and then from right to left (that is, from left to right in odd level, from right to left in even level)

#### 3. code

```# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
levels = []
if not root:
return []
queue = [root]
node = root
level = 1
while queue:
res = []
n = len(queue)
for i in range(0, n):
node = queue.pop(0)
if level % 2 == 1:
res.append(node.val)
else:
res.insert(0, node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
levels.append(res)
level += 1
return levels
```
Published 8 original articles, praised 0, visited 622

Posted on Fri, 13 Mar 2020 09:08:41 -0400 by NoName.ba