題目描述
輸入描述:
輸入的第一行表示節點的個數n(1 ≤ n ≤ 1000,節點的編號爲0到n-1)組成, 下面是n-1行,每行有兩個整數,第一個數表示父節點的編號,第二個數表示子節點的編號
輸出描述:
輸出樹的高度,爲一個整數
輸入
5 0 1 0 2 1 3 1 4
輸出
3
這道題開始我是想到用tree型結構來做,但是代碼寫到後來編不下去了,感覺這條路行不通(因爲題目中需要查找父節點)。於是看了其他人的思路,發現有人用HashMap來做,構造兩個hashmap分別來存放父節點和其子節點的個數,子節點以及子節點的深度。其實就是用了類似於數組索引的思想。//做題時,不要被其表面所迷惑,要先自己想想還有沒有可能用更方便的方法
public static void main(String[] args){Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
int num = sc.nextInt();
HashMap<Integer,Integer> tree = new HashMap();
HashMap<Integer,Integer> child_deep = new HashMap();
//樹一開始根結點爲0,孩子結點個數爲0
tree.put(0,0);
//孩子結點爲0,深度爲1
child_deep.put(0,1);
int dep = 0;
int max = 1;
for (int i = 0;i<num-1;i++){
int father = sc.nextInt();
int son = sc.nextInt();
//ArrayList裏面是contains
//樹裏面不包含父節點或者兒子已滿的情況,忽略
if(!tree.containsKey(father) || tree.get(father) >=2 ){
continue;
}
//父親的孩子數+1
tree.put(father,tree.get(father)+1);
//孩子變爲另一個父親
tree.put(son,0);
//深度+1
child_deep.put(son,child_deep.get(father)+1);
dep = child_deep.get(son);
if(max<dep ){
max = dep;
}
}
System.out.println(max);
}
}