22-从上往下打印二叉树

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

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function PrintFromTopToBottom(root)
{
    // write code here
    if(root == null) return [];
    var tree = [], res = [];
    tree.push(root);
    while(tree.length){
        var temp = tree.shift();
        res.push(temp.val)
        if(temp.left){
            tree.push(temp.left)
        };
        if(temp.right){
            tree.push(temp.right);
        }
    }
    return res;
}
发布了83 篇原创文章 · 获赞 0 · 访问量 2001

猜你喜欢

转载自blog.csdn.net/weixin_43655631/article/details/104033791
今日推荐