107. Binary Tree Level Order Traversal II(js)

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;
    
};
原文地址:https://www.cnblogs.com/xingguozhiming/p/10713153.html