题目
难度级别:简单
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
解题思路
通过广度优先搜索,创建队列用于存储待遍历层。 循环待遍历层的当前节点,依次加入当前层,若当前节点有left值或right值,将其值加入队列中。
const levelOrderBottom = function(root) {
if (root === null) return []
const res = []
const queue = []
queue.push(root)
while(queue.length) {
const currentLevel = []
const length = queue.length
for (let i = 0; i < length; i++) {
const currentNode = queue.shift()
currentLevel.push(currentNode.val)
if (currentNode.left) queue.push(currentNode.left)
if (currentNode.right) queue.push(currentNode.right)
}
res.unshift(currentLevel)
}
return res
};
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii
网友评论