首页 > Web开发 > 详细

107. Binary Tree Level Order Traversal II(js)

时间:2019-04-15 22:55:10      阅读:101      评论:0      收藏:0      [点我收藏+]

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).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   /   9  20
    /     15   7

 

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [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) {
    let res=[];
    if(!root) return res;
    let q=[];
    q.push(root);
    let stack=[];
    while(q.length>0){
        let count=0;
        let size=q.length;
        let curr=[];
        while(count<size){
            let currNode=q.shift();
            curr.push(currNode.val);
            if(currNode.left) q.push(currNode.left);
            if(currNode.right) q.push(currNode.right);
            count++;
        }
        stack.push(curr)
    }
    while(stack.length>0){
        res.push(stack.pop());
    }
    return res;
    
};

 

107. Binary Tree Level Order Traversal II(js)

原文:https://www.cnblogs.com/xingguozhiming/p/10713153.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!