• 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;
        
    };
  • 相关阅读:
    6.8
    6.7
    6.2
    6.1儿童节
    5.24
    5.22
    5.18
    5.17
    Visual Studio开始一个HelloWorld的enclave程序
    以太坊MPT树的HP(Hex-Prefix)编码
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10713153.html
Copyright © 2020-2023  润新知