1. 题目描述
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
2. 实现思路
对于这道题目,对二叉树进行层序遍历,最直接的方法就是使用BFS(广度优先遍历)。
首先创建一个队列,将当前你的节点放进去,队列中的节点始终是当前层的节点。按顺序出列,加入结果中,并将当前节点的子节点加入到队列中。
重复上述步骤,直到队列为空,就遍历完了整个二叉树。
3. 代码实现
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrderBottom = function(root) {
if(!root) {
return []
}
const queue = []
queue.push(root)
const res = [] // 用来储存最后的结果
while(queue.length){
const subRes = [] // 用来储存每一层的节点值
const levelSize = queue.length
for(let i = 0; i < levelSize; i++){
const cur = queue.shift()
subRes.push(cur.val)
if(cur.left){
queue.push(cur.left)
}
if(cur.right){
queue.push(cur.right)
}
}
res.unshift(subRes)
}
return res
};