I. 从上到下打印二叉树

57 阅读1分钟

I. 从上到下打印二叉树

题目描述:

从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。 例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回:

[3,9,20,15,7]

解法:

/**
 * 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){
        return [];
    }

    let temp=[root];
    const res=[];
    while(temp.length!==0){
        // 更新数组值
        temp.forEach(item=>{
            res.push(item.val);
        })
        // 更新缓存每一层的数组
        const newTemp=[];
        temp.forEach(item=>{
            if(item.left){
                newTemp.push(item.left)
            }
             if(item.right){
                newTemp.push(item.right)
            }
        })
        temp=[...newTemp]
    }
    return res;
};