题目
给定一个二叉树,返回其节点值自底向上的层序遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如: 给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其自底向上的层序遍历为:
[
[15,7],
[9,20],
[3]
]
来源:力扣(LeetCode)leetcode-cn.com/problems/bi…
解题思路
- 根据题目要求,需要逐层遍历二叉树,我们可以用一个队列来遍历
- 将当前层的节点入队列,再通过for循环取队列中节点的值,for循环的长度就是队列当前节点个数。循环的同时将节点出队列,如果节点有子节点则子节点入队列。按要求自底向上返回数组,所以树底层的节点插入数组最前面
3. 重复第2步
代码实现
var levelOrderBottom = function(root) {
if (!root) return []
const queue = [root]
const ans = []
while(queue.length) {
const arr = []
const len = queue.length
//打印当层的节点
for (let i = 0; i < len; i++) {
//当层节点出队列,并记录节点的值
const node = queue.shift()
arr.push(node.val)
//添加下一层节点
if (node.left) queue.push(node.left)
if (node.right) queue.push(node.right)
}
//树底层的节点插入数组最前面
ans.unshift(arr)
}
return ans
};
如有错误欢迎指出,欢迎一起讨论!