天天看點

劍指offer JS題解 (22)從上到下列印二叉樹

題目描述

從上往下列印出二叉樹的每個節點,同層節點從左至右列印。

解題思路

層次列印樹,其實就是樹的廣度周遊,利用隊列的FIFO的特點,從上到下從左到右列印結點。

Code

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function PrintFromTopToBottom(root)
{
    // write code here
    if(!root) return [];
    let queue=[],res=[];
    queue.push(root);
    while(queue.length!=0){
        node=queue.shift();
        res.push(node.val);
        if(node.left) queue.push(node.left);
        if(node.right) queue.push(node.right);
    }
    return res;
}
           

運作環境:JavaScript (V8 6.0.0)

運作時間:11ms

占用記憶體:5344k