java二叉树demo

最近看了哈二叉树的demol,呃....仍然有点模糊不懂,呵呵,貌似那个demol的单词也忘记了,问了哈静静同学才记起来
呵呵,不废话了,贴上二叉树的demol 整理了一部分,还有一部分待定,呵呵 以后再修改吧


public class Tree {

private int data;// 数据节点
private Tree left;// 左子树
private Tree right;// 右子树

public Tree(int data) {
this.data = data;
this.left = null;
this.right = null;
}

/**
* @param args
*/
public static void main(String[] args) {
int[] input = { 4, 2, 6, 1, 3, 5, 7 };
Tree tree = createTree(input);
System.out.print("前序遍历:");
preOrder(tree);
System.out.print("\n中序遍历:");
midOrder(tree);
System.out.print("\n后序遍历:");
posOrder(tree);
}

/**
* 创建二叉树,返回根结点
*
* @param input
* @return
*/
public static Tree createTree(int[] input) {
Tree root = null;//用于长时间存储数据,以供temp循环完毕后更改成为原始值
Tree temp = null;//用于动态比较的临时值
for (int i = 0; i < input.length; i++) {
// 创建根节点
if (root == null) {
root = temp = new Tree(input[i]);//给予初始值
} else {
// 回到根结点
temp = root;//在此处保持临时值的原始性
// 添加节点
//循环判断初始值是否和当前比较的值相同,如果相通直接跳出循环
while (temp.data != input[i]) {
//当前循环要比较的值与根节点x进行比较
if (input[i] <= temp.data) {
if (temp.left != null) {
temp = temp.left;
} else {
//如果tree对象里面的temp.left对象为空就将当前循环的对象值放入其中
temp.left = new Tree(input[i]);
}
} else {
if (temp.right != null) {
temp = temp.right;
} else {
temp.right = new Tree(input[i]);
}
}
}
}
}
return root;
}

/**
* 前序遍历
*
* @param tree
*/
public static void preOrder(Tree tree) {
if (tree != null) {
System.out.print(tree.data + " ");
preOrder(tree.left);
preOrder(tree.right);
}
}

/**
* 中序遍历
*
* @param tree
*/
public static void midOrder(Tree tree) {
if (tree != null) {
midOrder(tree.left);
System.out.print(tree.data + " ");
midOrder(tree.right);
}
}

/**
* 后序遍历
*
* @param tree
*/
public static void posOrder(Tree tree) {
if (tree != null) {
posOrder(tree.left);
posOrder(tree.right);
System.out.print(tree.data + " ");
}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值