/**
* Created by albert.bai on 2014/11/4.
*/
public class BiTree {
private TreeNode root = null;
private static class TreeNode {
private TreeNode liftChild = null;
private TreeNode rightChild = null;
// private TreeNode parent =null;
private int value;
public TreeNode(int value) {
this.value = value;
this.liftChild = null;
this.rightChild = null;
// this.parent =null;
}
}
//实现一颗空的二叉树
public BiTree() {
root = null;
}
//递归的插入数据
public TreeNode insert(int value) {
root = insert(value, root);
return root;
}
/*
* 当二叉树为空时 直接将值赋予root 当value小于等于父节点,将value赋予左节点 反之赋予右节点
* value 插入的值
* treeNode 父节点
* */
private TreeNode insert(int value, TreeNode treeNode) {
//当父节点为空时
if (treeNode == null) {
treeNode = new TreeNode(value);
} else {
if (value <= treeNode.value) {
treeNode.liftChild = insert(value, treeNode.liftChild);
} else if (value > treeNode.value) {
treeNode.rightChild = insert(value, treeNode.rightChild);
}
}
return treeNode;
}
//为数值输入构建二叉树
public void buildTree(int[] datas) {
for (int i = 0; i < datas.length; i++) {
insert(datas[i]);
}
}
//递归前序打印二叉树
public void preOrder() {
preOrder(root);
System.out.println();
}
private void preOrder(TreeNode treeNode) {
if (treeNode == null) {
return;
} else {
System.out.print(treeNode.value);
preOrder(treeNode.liftChild);
preOrder(treeNode.rightChild);
}
}
//递归中续遍历一棵树
public void inOrder() {
inOrder(root);
System.out.println();
}
private void inOrder(TreeNode treeNode) {
if (treeNode == null) {
return;
} else {
inOrder(treeNode.liftChild);
System.out.print(treeNode.value);
inOrder(treeNode.rightChild);
}
}
//递归后续遍历一棵树
public void postOrder() {
postOrder(root);
System.out.println();
}
private void postOrder(TreeNode treeNode) {
if (treeNode == null) {
return;
} else {
postOrder(treeNode.liftChild);
postOrder(treeNode.rightChild);
System.out.print(treeNode.value);
}
}
public static void main(String[] args) {
int[] datas = {1, 2, 4, 3, 7, 5, 6};
BiTree biTree = new BiTree();
biTree.buildTree(datas);
biTree.postOrder();
biTree.inOrder();
biTree.preOrder();
}
}
Java 实现二叉查找树
最新推荐文章于 2024-08-14 23:12:09 发布