剑指 Offer 32 - II. 从上到下打印二叉树 II
正题
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
解析:
本题算法的实质是优先广度的二叉树层序遍历,在遍历每一层时记录下当前层的所有节点的 val值放入一个数组中,在最终将所有层的数组放入最终返回的数组中,所以最终返回的数组是: 元素为每层所有节点val值的数组,本质是二维数组
二叉树的层序遍历
首先实现二叉树的层序遍历:
var levelOrder = function(root) {
const quene = root ? [root] : []
while(quene.length) {
const size = quene.length
for (let index = 0 ; index < size; index++) {
const node = quene.shift()
node.left ? quene.push(node.left) : ''
node.right ? quene.push(node.right) : ''
}
}
}
for循环中就是每一层的节点,可以理解为一个 for 循环就是在遍历一层节点。
那么我们需要记录并保存这些节点的 val
利用变量 level保存每一层的所有节点。
最后再将所有层保存下来,放入到新的数组中,形成最终结果的二维数组
完整代码:
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function(root) {
const quene = root ? [root] : []
const res = []
while(quene.length) {
const size = quene.length // 结果数组
const level = [] // 每层节点 val 数组
for (let index = 0 ; index < size; index++) {
// 层遍历
const node = quene.shift()
node.left ? quene.push(node.left) : ''
node.right ? quene.push(node.right) : ''
level.push(node.val) // 保存当前层的某个 node 的值
}
res.push(level) // 将层存储
}
return res // 返回结果
}
二叉树的层序遍历是关键,了解层序遍历算法的同时,才能够将层分离出来,达到灵活运用。