java写二叉树算法
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
java写二叉树算法,实现添加数据形成二叉树功能,并打印出来时间:2009-09-25 09:11:11来源:网络作者:未知点击:0次
public class MyTest {
private myTree tree;
/**
*二叉树的插入,参数为(关键字,数据)
*
**/
public void insert(int key, int d
public class MyTest {
private myTree tree;
/**
*二叉树的插入,参数为(关键字,数据)
*
**/
public void insert(int key, int data) {
if (tree == null) {
tree = new myTree();
tree.key = key;
tree.data = data;
} else {
myTree newTree = new myTree();
newTree.key = key;
newTree.data = data;
myTree parent = tree;
while (true) {
if (newTree.key < parent.key) {
if (parent.leftChild == null) {
parent.leftChild = newTree;
return;
} else {
parent = parent.leftChild;
}
} else if (newTree.key > parent.key) {
if (parent.rightChild == null){ parent.rightChild = newTree;
return;
} else {
parent = parent.rightChild;
}
}
}
}
}
/**
* 二叉树的查找,参数为(关键字),返回值为myTree的一个实例*
* **/
public myTree find(int key) {
if (tree == null)
return null;
myTree curr = new myTree();
curr.key = key;
myTree parent = tree;
while (true) {
if (parent == null) {
return null;
} else if (curr.key == parent.key) {
return parent;
} else if (curr.key > parent.key) {
parent = parent.rightChild;
} else if (curr.key < parent.key) {
parent = parent.leftChild;
}
}
}
/*
*
* 递归的二叉树中序遍历
*
*
*/
private static void midOrder(myTree tree) {
if (tree != null) {
midOrder(tree.leftChild);
System.out.println(tree + "," + tree.key + "," + tree.data);
midOrder(tree.rightChild);
}
}
/*
* 前序遍历
*/
private static void frontOrder(myTree tree) {
if (tree != null) {
System.out.println("" + tree.key + " , " + tree.data);
frontOrder(tree.leftChild);
frontOrder(tree.rightChild);
}
}
public static void main(String[] args) {
System.out.println("Tree view Begin");
MyTest t1 = new MyTest();
t1.insert(8, 25);
t1.insert(5, 9);
t1.insert(58, 87);
t1.insert(13, 82);
t1.insert(4, 8);
t1.insert(12, 54);
t1.insert(53, 123);
t1.insert(56, 47);
t1.insert(2, 75);
t1.insert(34, 5);
t1.insert(6, 23);
System.out.println("现在开始遍历:");
frontOrder(t1.tree);
midOrder(t1.tree);
}
}
class myTree {
int key;
int data;
myTree leftChild;
myTree rightChild;
}
本篇文章来源于:开发学院 原文链接:/2009/0925/15766.php