107 Binary Tree Level Order Traversal II
题目描述
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
给定二叉树,返回其自下而上的遍历顺序的节点值
- 输入
3
/ \
9 20
/ \
15 7
- 输出
[
[15,7],
[9,20],
[3]
]
解法
let levelOrderBottom = function(root) {
if (!root) { return []} // 不能少,不然lever.push报错
let result = [] // 用来存放最终结果
let queue = [root]
while(queue.length){
let level = []; // 存放每一层的元素
let len = queue.length;
for(let i = 0; i < len; i++){ // 通过遍历将当前层所有元素放进level
let node = queue.shift()
level.push(node.val)
if(node.left){queue.push(node.left) } // 如果该节点下一层还有值,则放入队列中,一下遍历继续取出
if(node.right) {queue.push(node.right)}
}
if(level.length) {result.push(level)}
}
return result.reverse() // 这样取出来的值从上往下一层一层取,结果要的是从底部网上
};
按照上面例子就是
1 queue = [3]
2 node = 3, level = [3], queue = []
3 node.left = 9, node.right = 20, queue = [9,20]
下一轮循环
1 queue = [9,20]
2 node = 9,level = [9],queue = [20]
3 node = 20,level = [9,20], queue = []
4 node.left = 15, node.right = 7,queue = [17,7]
再一次下一轮。。。
网友评论