牛客——从上往下打印二叉树

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

思路:
害,这不就是树的层次遍历吗。循环借助辅助数组存放当前层。

代码实现:(ps:不要忘记前期判断,我开始没每判断搞了十分钟都不知道哪错了,千万不要偷懒呀)

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

                tepNode = tep[0];
                res.push(tepNode.val);

                if (tepNode.left) {
                    tep.push(tepNode.left);
                }
                if (tepNode.right) {
                    tep.push(tepNode.right);
                }
                tep.shift();
            }

            return res;

        }

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章