題目描述:
從上往下打印出二叉樹的每個節點,同層節點從左至右打印。
思路:
害,這不就是樹的層次遍歷嗎。循環藉助輔助數組存放當前層。
代碼實現:(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;
}