剑指offer-从上到下打印二叉树-JavaScript实现

1.题目描述:

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

2.上代码:

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

猜你喜欢

转载自blog.csdn.net/qq_42099097/article/details/107320300