java实现二叉树的添加和中序,前序排列;求二叉树的高度

package com.kane.test;
class BiTree{
private int data;//存放的数据
private BiTree left;//左子树
private BiTree right;//右子树
public BiTree(int x) {
data=x;
}
public void add(BiTree x) {
if (x.data<this.data) {//值小的给左子树
if (left==null) {
left=x;
}
else {
left.add(x);//如果左边为空就添加,不为空就递归添加
}
}
else {
if (right==null) {
right=x;
}
else {
right.add(x);
}
}
}
/**
* 用递归解决中序遍历
*/
public void midTravel() {
if (left!=null) {//要判断,不让有BUG
left.midTravel();
}
System.out.println(data);
if (right!=null) {
right.midTravel();
}
}
/**
* 用递归解决先序遍历
*/
public void preTravel() {
System.out.println(data);
if (left!=null) {//要判断,不让有BUG
left.preTravel();
}

if (right!=null) {
right.preTravel();
}
}
}
public class TestBinaryTre {
public static void main(String[] args) {
BiTree root=new BiTree(12);
root.add(new BiTree(9));
root.add(new BiTree(5));
root.add(new BiTree(8));
root.add(new BiTree(15));
root.add(new BiTree(20));
root.preTravel();
root.midTravel();
}

}


求二叉树的高度

package com.zhangle.arithmetic;


class BiTree {
private int data;// 存放的数据
private BiTree left;// 左子树
private BiTree right;// 右子树


public BiTree(int x) {
data = x;
}


public void add(BiTree x) {
if (x.data < this.data) {// 值小的给左子树
if (left == null) {
left = x;
} else {
left.add(x);// 如果左边为空就添加,不为空就递归添加
}
} else {
if (right == null) {
right = x;
} else {
right.add(x);
}
}
}
/**
* 二叉树的高度就是它的左子树和右子树中高度最大值 + 1
* @param x
* @return
*/


public int height(BiTree x) {
int a=0,b=0;
if (x.left!=null) {
a=height(x.left)+1;
}

if (x.right!=null) {
b=height(x.right)+1;
}


return a>b?a:b;
}



}


public class HeightBiTree {
public static void main(String[] args) {
BiTree root = new BiTree(12);
root.add(new BiTree(9));
root.add(new BiTree(5));
root.add(new BiTree(8));
root.add(new BiTree(15));
root.add(new BiTree(20));
System.out.println(root.height(root)+1);
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值