题目
求二叉树的深度。第一行n表示二叉树节点个数,接下来的n-1行第一个数表示根节点,第二个节点表示孩子节点。
5
0 1
0 2
1 3
1 4
思想
第一步:存二叉树(用二维数组存)
第二步:采用先序遍历,求深度
代码
public class Main {
private static int max=0;//用于存二叉树最大的深度
private static int now=0;//当前的深度
public static void main(String[] args) {
//输入
Scanner s=new Scanner(System.in);
int size=Integer.parseInt(s.nextLine());
int [][]a=new int[size][2];
for(int i=0;i<size;++i){
a[i][0]=-1;
a[i][1]=-1;
}
while(s.hasNextLine()){
String str=s.nextLine();
String[] temp=str.split("\\s+");
if(temp.length!=2){
break;
}
int parent=Integer.parseInt(temp[0]);//根节点
int child=Integer.parseInt(temp[1]);//孩子节点
if(a[parent][0]==-1){
a[parent][0]=child;
}else{
a[parent][1]=child;
}
}
//进行深度遍历求二叉树深度
boolean v[]=new boolean[size];//标记节点是否已经被放问了
go(a,v,0);
System.out.println(max);
}
public static void go(int[][]a,boolean[] v,int position){
if(position==-1){
max=now>max?now:max;
return ;
}
v[position]=true;
now++;
go(a,v,a[position][0]);
go(a,v,a[position][1]);
now--;//左右试探完成后回溯
return;
}
}