剑指offer二叉树打印

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function Print(pRoot)
{
// write code here
let res=[];
if(pRoot.length<1)
return res;
for(let i=0;pRoot.length>1;i++){
let item=[]
for(let j=0;j<Math.pow(2,i)&&pRoot.lenght>1;j++){
item.push(pRoot.shift())
}
res[i]=item;
}
return res;

}

为什么会数组越界

  • 读题不仔细
  • 审题不严格
  • 基础不扎实

递归!import

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function Print(pRoot)
{
const arr=[];
function printTree(root,deepth=0){
if(root===null) return;
arr[deepth]?'':arr[deepth]=[];
arr[deepth].push(root.val);
printTree(root.left,deepth+1);
printTree(root.right,deepth+1);
}
printTree(pRoot);
return arr
}
module.exports = {
Print : Print
};