2019-08-07笔试题2:神州数码

题目描述:
现在有一棵合法的二叉树,树的节点都是用数字表示,
现在给定这棵树上所有的父子关系,求这棵树的高度
输入
输入的第一行表示节点的个数n(1<=n<=1000,节点的编号为0到n-1)组成,
下面是n-1行,每行有两个整数,第一个数表示父节点的编号,第二个数表示子节点的编号

输出
输出树的高度,为一个整数

样例输入
5
0 1
0 2
1 3
1 4
样例输出
3

个人实现代码:这问题的关键是如何利用输入值构建二叉树,并且知道递归求出树的高度

TreeNode(int num){
            this.num=num;
        }
    }
 ;
    // 计算高度
    public  int height(TreeNode node){
//    递归循环,返回树的高度
        if(node==null){
            return 0;
        }
        int nLeft = height(node.left);
        int nRight = height(node.right);
        return (nLeft>nRight)?(nLeft+1):(nRight+1);
    }

    public static void main(String[] args) {
        //
        TreeHeight treeheight=new TreeHeight();
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();//节点的个数
//
        HashMap map=new HashMap();
        int j=n-1;
//    构建树
//    父节点
        TreeNode parent=new TreeNode(0);
//    加入Map
        map.put(0, parent);
        while(j>0){
//       获得节点的值
            int parentval=sc.nextInt();
            int childval=sc.nextInt();
//       找到节点,并成为该节点的子节点
            TreeNode node=map.get(parentval);
            if(node.left==null){
//          左节点
                TreeNode leftchild=new TreeNode(childval);
                map.put(childval, leftchild);
                node.left=leftchild;

            }else{
//          右节点
                TreeNode rightchild=new TreeNode(childval);
                map.put(childval, rightchild);
                node.right=rightchild;
            }
            j--;
        }
        int max=treeheight.height(parent);
        System.out.println(max);
    }
}

你可能感兴趣的:(2019-08-07笔试题2:神州数码)