java二叉树的实现和遍历

时间:2023-03-09 06:27:29
java二叉树的实现和遍历
/*
* Java实现二叉树
*/
public class BinaryTree { int treeNode;
BinaryTree leftTree;
BinaryTree rightTree; public BinaryTree(int Data) {
// TODO Auto-generated constructor stub
treeNode=Data;
leftTree=null;
rightTree=null;
} public void insert(BinaryTree node,int data) {
if(data >node.treeNode){
if(node.rightTree==null){
rightTree=new BinaryTree(data);
}else{
this.insert(node.rightTree, data);
}
}else{
if (node.leftTree==null) {
leftTree=new BinaryTree(data);
}else{
this.insert(node.leftTree, data);
}
}
}
}
/*
* 对定义二叉树的,先序遍历,中序遍历,后序遍历
*/
public class BinaryTreeOrder { public static void preOrder(BinaryTree root) { // 先序遍历
if (root != null) {
System.out.print(root.treeNode + "-");
preOrder(root.leftTree);
preOrder(root.rightTree);
}
} public static void inOrder(BinaryTree root) { // 中序遍历 if (root != null) {
inOrder(root.leftTree);
System.out.print(root.treeNode + "--");
inOrder(root.rightTree);
}
} public static void postOrder(BinaryTree root) { // 后序遍历 if (root != null) {
postOrder(root.leftTree);
postOrder(root.rightTree);
System.out.print(root.treeNode + "---");
}
} public static void main(String[] args) {
int[] array = { 12, 76, 35, 22, 16, 48, 90, 46, 9, 40 };
BinaryTree root = new BinaryTree(array[0]); // 创建二叉树
for (int i = 1; i < array.length; i++) {
root.insert(root, array[i]); // 向二叉树中插入数据
}
System.out.println("先序遍历:");
preOrder(root);
System.out.println();
System.out.println("中序遍历:");
inOrder(root);
System.out.println();
System.out.println("后序遍历:");
postOrder(root);
}
}