定义一棵二叉树的高度就是从根到叶子的最长距离。试编码求二叉树的高度。

//其思想就是,若二叉树为空,则其深度为0,否则,其深度等于左子树和右子树的深度的最大值加1:
class BiTree{
	
	private int data;
	private BiTree left;
	private BiTree right;
	
	public BiTree(int x)
	{
		data = x;
	}
	
	//t为待插入的节点
	public void add(BiTree t)
	{
		//判断是左子树
		if(t.data < this.data){
			//如果左子树为空,则t为左子树
			if(left == null)
				left = t;
			//否则递归调用增加,与左子树增加,再判断                                                  
			else
				left.add(t);
		}
		else{
			if(right == null)
				right = t;
			else
				right.add(t);
		
		}
	}
	
	
	public int length(BiTree t){
		int depth1 = 0;
		int depth2 = 0;
		
		if(t == null ) return 0;
		//右子树的深度
		depth1 = length(t.right);
		//左子树的深度
		depth2 = length(t.left);
		
		if(depth1>depth2)
			return depth1+1;
			else
				return depth2+1;
		
	}
}

public class BinaryTree {

	public static void main(String[] args) {
		
		BiTree t = new BiTree(12);
		t.add(new BiTree(9));
		t.add(new BiTree(5));
		t.add(new BiTree(8));
		t.add(new BiTree(15));
		t.add(new BiTree(20));
		
		//求二叉树的高度,传入二叉树
		int deep = t.length(t);
		System.out.println(deep);
		
	}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值