用js刷剑指offer(从上到下打印二叉树)

题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。
牛客网链接

js代码

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function PrintFromTopToBottom(root)
{
    // write code here
    if (!root) return []
    const queue = []
    const res = []
    queue.push(root)
    while (queue.length !== 0){
        let node = queue.shift()
        if (node.left) {
            queue.push(node.left)
        }
        if (node.right) {
            queue.push(node.right)
        }
        res.push(node.val)
    }
    return res
}
posted @ 2019-10-10 15:08  1Shuan  阅读(298)  评论(0编辑  收藏  举报