【leetcode】剑指 Offer 32 - II. 从上到下打印二叉树 II(js实现)

1. 题目

剑指 Offer 32 - II. 从上到下打印二叉树 II
【leetcode】剑指 Offer 32 - II. 从上到下打印二叉树 II(js实现)_第1张图片

2. debug

【leetcode】剑指 Offer 32 - II. 从上到下打印二叉树 II(js实现)_第2张图片

3. 代码实现

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function(root) {
    if (root === null) return []
    let res = [], tmp = [root]
    while (tmp.length) {
        let childtmp = [], level = [] // 临时存储此层的所有子节点,每一层的val
        console.log('tmp', tmp)
        for (let i = 0; i < tmp.length; i++) {
            console.log('tmpi & tmpi.val', tmp[i], tmp[i].val)
            level.push(tmp[i].val)
            if (tmp[i].left) childtmp.push(tmp[i].left)
            if (tmp[i].right) childtmp.push(tmp[i].right)
        }
        tmp = childtmp
        res.push(level)
    }
    return res
};

你可能感兴趣的:(javascript,leetcode,开发语言)