题目描述:
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
思路:
害,这不就是树的层次遍历吗。循环借助辅助数组存放当前层。
代码实现:(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;
}

本文详细解析了从上至下、从左至右打印二叉树各节点的层次遍历算法,通过循环和辅助数组实现,确保了遍历顺序的正确性。
1万+

被折叠的 条评论
为什么被折叠?



