1. 题目描述

从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印。

2. 思路分析

借助队列这种“先入先出”的线性数据结构即可。每次访问队列中的元素的时候,输出它的值,并且将其非空左右节点放入队列中。直到队列为空,停止输出,结束函数循环即可。

3. 代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class TreeNode {
constructor(value, left = null, right = null) {
this.value = value
this.left = left
this.right = right
}
}

/**
* 层级遍历二叉树
* @param {TreeNode} root
*/
function levelTravel(root) {
const queue = [root]
while (queue.length) {
let first = queue.shift()
console.log(first.value)

if (first.left) {
queue.push(first.left)
}

if (first.right) {
queue.push(first.right)
}
}
}

/**
*
*/

const root = new TreeNode(10, new TreeNode(6, new TreeNode(4), new TreeNode(8)), new TreeNode(14, new TreeNode(12), new TreeNode(16)))

levelTravel(root)