您的位置:首页 > 其它

二叉树之实现排序二叉树

2015-10-22 08:51 204 查看
package me.wcy.j2se.datastructure;

/**
* 排序二叉树
*
* @author chenyan.wang
*
*/
public class BinaryTree {

public static void main(String[] args) {
BinaryTree biTree = new BinaryTree();
int[] data = { 2, 8, 7, 4, 9, 3, 1, 6, 7, 5 };
biTree.buildTree(data);
System.out.print("中序遍历:");
biTree.inOrder();
System.out.println();
System.out.print("先序遍历:");
biTree.preOrder();
System.out.println();
System.out.print("后序遍历:");
biTree.postOrder();
System.out.println();
}

private TreeNode root;

public BinaryTree() {
}

/**
* 将data插入到排序二叉树中
*
* @param data
*/
public void insert(int data) {
TreeNode node = new TreeNode(data);
if (root == null) {
root = node;
} else {
TreeNode current = root;
TreeNode parent;
while (true) {// 寻找插入位置
parent = current;
if (data < parent.data) {
current = parent.left;
if (current == null) {
parent.left = node;
return;
}
} else {
current = parent.right;
if (current == null) {
parent.right = node;
return;
}
}
}
}
}

/**
* 将数值输入构建二叉树
*
* @param data
*/
public void buildTree(int[] data) {
for (int n : data) {
insert(n);
}
}

/**
* 中序遍历
*/
public void inOrder() {
inOrder(root);
}

public void inOrder(TreeNode localRoot) {
if (localRoot != null) {
inOrder(localRoot.left);
System.out.print(localRoot.data + " ");
inOrder(localRoot.right);
}
}

/**
* 先序遍历
*/
public void preOrder() {
preOrder(root);
}

public void preOrder(TreeNode localRoot) {
if (localRoot != null) {
System.out.print(localRoot.data + " ");
preOrder(localRoot.left);
preOrder(localRoot.right);
}
}

/**
* 后序遍历
*/
public void postOrder() {
postOrder(root);
}

public void postOrder(TreeNode localRoot) {
if (localRoot != null) {
postOrder(localRoot.left);
postOrder(localRoot.right);
System.out.print(localRoot.data + " ");
}
}

}

输出结果:

中序遍历:1 2 3 4 5 6 7 7 8 9

先序遍历:2 1 8 7 4 3 6 5 7 9

后序遍历:1 3 5 6 4 7 7 9 8 2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: