牛客——從上往下打印二叉樹

題目描述:
從上往下打印出二叉樹的每個節點,同層節點從左至右打印。

思路:
害,這不就是樹的層次遍歷嗎。循環藉助輔助數組存放當前層。

代碼實現:(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;

        }

在這裏插入圖片描述

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