Java編程-樹的高度

現在有一棵合法的二叉樹,樹的節點都是用數字表示,現在給定這棵樹上所有的父子關係,求這棵樹的高度
輸入描述:
輸入的第一行表示節點的個數n(1 ≤ n ≤ 1000,節點的編號爲0到n-1)組成,
下面是n-1行,每行有兩個整數,第一個數表示父節點的編號,第二個數表示子節點的編號


輸出描述:
輸出樹的高度,爲一個整數
示例1

輸入

5
0 1
0 2
1 3
1 4

輸出

3
代碼如下:
鏈接:https://www.nowcoder.com/questionTerminal/4faa2d4849fa4627aa6d32a2e50b5b25
來源:牛客網

import java.util.HashMap;
import java.util.Scanner;
 
public class Main {
 
    public static void main(String[] args) {
 
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        String result = "";
        // 樹的深度Map、節點孩子數量Map
        HashMap<Integer, Integer> deep = new HashMap<>();
        HashMap<Integer, Integer> childNum = new HashMap<>();
        deep.put(0, 1);
        childNum.put(0, 0);
        // 默認樹的深度爲1
        int max = 1;
        int myDeep = 0;
        for (int i = 0; i < n - 1; i++) {
            int parent = scanner.nextInt();
            int num = scanner.nextInt();
            // 不包含父節點或者孩子數目超過兩個,則跳過
            if (!deep.containsKey(parent) || childNum.get(parent) >= 2) {
                continue;
            }
            // 樹的深度加一
            myDeep = deep.get(parent) + 1;
            // 子節點和樹的深度
            deep.put(num, myDeep);
            // 存父節點,其子節點的數量加一
            childNum.put(parent, (childNum.get(parent) + 1));
            // 存子節點,其子節點數量爲0
            childNum.put(num, 0);
            if (myDeep > max) {
                max = myDeep;
            }
        }
        System.out.println(max);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章