您的位置:首页 > 编程语言 > Java开发

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

2014-03-22 11:08 633 查看
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);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐