构造二叉树,并求二叉树的深度

69 篇文章 0 订阅

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
//构造二叉树,并求二叉树的深度

public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Map<Integer,ArrayList<Integer>> map=new TreeMap<Integer,ArrayList<Integer>>();
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextInt()){
            
            int key=sc.nextInt();
            if(!map.containsKey(key)){
                ArrayList<Integer> list=new ArrayList<Integer>();
                list.add(sc.nextInt());
               map.put(key, list);
            }
            else{
                ArrayList<Integer> list=map.get(key);
                list.add(sc.nextInt());
                map.put(key, list);
            }
            
        }
        TreeNode root = new TreeNode(0);
        if(map==null) return;

        LinkedList<TreeNode> queue = new LinkedList<>();

        queue.add(root);
        TreeNode current;
        while (!queue.isEmpty()) {
            
            current=queue.poll();
            int key=current.val;
            if(!map.containsKey(key)) continue;
            ArrayList<Integer> list=map.get(key);
            if(list==null||list.size()<1) continue;
            int n=list.size();
            if(n==1){
                int tmp=list.get(0);
                TreeNode node=new TreeNode(tmp);
                if(tmp==2*key+1) root.left=node;
                else if(tmp==2*key+2) root.right=node;
                queue.add(node);
            }
            else if(n==2){
                int tmp=list.get(0);
                TreeNode node=new TreeNode(tmp);
                
                if(tmp==2*key+1) root.left=node;
                else if(tmp==2*key+2) root.right=node;
                int tmp1=list.get(1);
                TreeNode node1=new TreeNode(tmp1);
                if(tmp1==2*key+1) root.left=node1;
                else if(tmp1==2*key+2) root.right=node1;
                queue.add(node);
                queue.add(node1);
            }
        }
       int x=maxDepth(root);
       System.out.println(x+1);
       
    }
    
    public static int maxDepth(TreeNode root) {
        return root == null ? 0 : (1 + Math.max(maxDepth(root.left), maxDepth(root.right)));
    } 
}
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) {
        val = x;
    }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值