//其思想就是,若二叉树为空,则其深度为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);
}
}
定义一棵二叉树的高度就是从根到叶子的最长距离。试编码求二叉树的高度。
最新推荐文章于 2022-03-03 21:34:37 发布