pwstrick / daily

一份搜集的前端面试题目清单、面试相关以及各类学习的资料(不局限于前端)
2.38k stars 242 forks source link

二叉树的层次遍历 II #1038

Open pwstrick opened 4 years ago

pwstrick commented 4 years ago

107. 二叉树的层次遍历 II

/**
 * 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 == null)
        return [];
    const stack = bfs(root);
    return stack.reverse();
};
function bfs(root) {
    const stack = [],
        queue = [root];
    while(queue.length) {
        const len = queue.length;
        let node, arr = []
        for(let i=0; i<len; i++) {
            node = queue[i];
            arr.push(node.val);
        }
        stack.push(arr);
        for(let i=0; i<len; i++) {
            node = queue.shift();
            node.left && queue.push(node.left);
            node.right && queue.push(node.right);
        }
    }
    return stack;
}