Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

13、二叉树的层次遍历 II #13

Open
conan1992 opened this issue Apr 1, 2020 · 0 comments
Open

13、二叉树的层次遍历 II #13

conan1992 opened this issue Apr 1, 2020 · 0 comments

Comments

@conan1992
Copy link
Owner

给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

例如:
给定二叉树 [3,9,20,null,null,15,7],
image
返回其自底向上的层次遍历为:
image

/**
 * 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) {
    if(!root||root.val===undefined){
        return []
    }
    var arr = new Array();
    var nodes = new Array()
    nodes.push(root)
    while(nodes.length){
        let arr2 = new Array();
        let arr3 = new Array()
        for(var attr in nodes){
            arr2.push( nodes[attr].val )
            nodes[attr].left && arr3.push(nodes[attr].left);
            nodes[attr].right && arr3.push(nodes[attr].right)
        }
        nodes = arr3
        arr.unshift( arr2 )
    }
    return arr
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant