二叉树最大宽度和高度(java)


题目描述 Description

给出一个二叉树,输出它的最大宽度和高度。
输入描述 Input Description

第一行一个整数n。

下面n行每行有两个数,对于第i行的两个数,代表编号为i的节点所连接的两个左右儿子的编号。如果没有某个儿子为空,则为0。
输出描述 Output Description

输出共一行,输出二叉树的最大宽度和高度,用一个空格隔开。
样例输入 Sample Input

5

2 3

4 5

0 0

0 0

0 0

import java.util.Scanner;
import java.util.Arrays;
class Node
{
	int data;
	Node left;
	Node right;
	public Node(int data)
	{
		this.data=data;
		this.left=null;
		this.right=null;
	}
}
public class Main
{
	static int lchild[]=new int[25];
	static int rchild[]=new int[25];
	static int width[]=new int[25];
	static int height;
	public static Node BuildTree(int data)
	{
		if(data==0) return null;
		Node root=new Node(data);
		root.left=BuildTree(lchild[data]);
		root.right=BuildTree(rchild[data]);
		return root;
	}
	public static void dfs(Node root,int x)
	{
		if(root!=null)
		{
			width[x]++;
			if(x>height) height=x;
			dfs(root.left,x+1);
			dfs(root.right,x+1);
		}
	}
	public static void main(String[] args)
	{
		Scanner in=new Scanner(System.in);
		while(in.hasNext())
		{
			int n=in.nextInt();
			Arrays.fill(width, 0);
			height=0;
			for(int i=1;i<=n;i++)
			{
				lchild[i]=in.nextInt();
				rchild[i]=in.nextInt();
			}
			Node root=BuildTree(1);
			dfs(root,1);
			int max_width=0;
			for(int i=1;i<=n;i++)
				if(width[i]>max_width) 
					max_width=width[i];
			System.out.println(max_width+" "+height);
		}
	}
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值