题目描述
现在有一棵合法的二叉树,树的节点都是用数字表示,现在给定这棵树上所有的父子关系,求这棵树的高度
输入描述:
输入的第一行表示节点的个数n(1 ≤ n ≤ 1000,节点的编号为0到n-1)组成,下面是n-1行,每行有两个整数,第一个数表示父节点的编号,第二个数表示子节点的编号
输出描述:
输出树的高度,为一个整数
思路:
主要还是使用递归的思想,根节点对应树的高度 = 孩子节点对应树的高度+1 ,当某个节点没有子节点时,说明是叶子节点开始回溯。
package test;
import java.util.Scanner;
public class TreeDepth
{
private static int[][] arr;
public static void main(String[] args) {
TreeDepth.init();
System.out.println(TreeDepth.getTreeDepth(0));;
}
private static int getTreeDepth(int parentNode) {
int[] childNode = getChildNode(parentNode);
if(childNode[0]==-1&&childNode[1]==-1)
return 1;
else
return Math.max(getTreeDepth(childNode[0]), getTreeDepth(childNode[1]))+1;
}
private static int[] getChildNode(int parentNode) {
int[] childNode = {-1,-1};
int index = 0;
for(int i= 0;i<arr.length;i++) {
if(arr[i][0]==parentNode)
childNode[index++] = arr[i][1];
if(index==2) break;
}
return childNode;
}
/**
* 初始化arr二维数组,存储父子关系节点
*/
private static void init() {
Scanner scn = new Scanner(System.in);
int len = scn.nextInt()-1;
arr = new int[len][2];
for(int i=0;i<len;i++) {
arr[i][0] = scn.nextInt();
arr[i][1] = scn.nextInt();
}
scn.close();
}
}