尝试一
result:答案正确:恭喜!您提交的程序通过了所有的测试用例
code:
import java.util.ArrayList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
//二叉树的深度
private int depth=0;
private TreeNode root=null;
private ArrayList<Integer> printList=new ArrayList<>();
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
/*重置二叉树深度和节点*/
depth=0;
this.root=root;
printList=new ArrayList<>();
//设置二叉树的深度
setDepth(this.root);
//打印二叉树
for(int i=1;i<=depth;++i){
print(i,1,this.root);
}
return printList;
}
/*寻找二叉树的深度(这是先序遍历)*/
private void setDepth(TreeNode root){
/*递归结束标识*/
if(root==null){
return ;
}
depth+=1;
setDepth(root.left);
setDepth(root.right);
}
/*
*now:表示第k层的节点
* i:标识打印第i层
* k:表示递归到了第k层
*/
private void print(int i,int k,TreeNode now){
if(i>depth || now ==null){
return;
}
if( k==i){//意思是递归到指定打印层i
printList.add(now.val);
}
print(i,k+1,now.left);
print(i,k+1,now.right);
}
}
思路:需要找到二叉树的深度,然后一层一层的打印。至于怎么到达指定层,用递归的方法。
结论
- 在递归时,有些参数不需要你写在递归函数的形参里面。那它定义为实例对象反而会是代码更清晰。