package xiangtu;
/**
* 通过二叉树排序
*
* @author 宋
*
*/
public class TreeSort {
public static void main(String[] args) {
int[] a = { 89, 33, 11, 5, 6, 26, 54, 12, 555, 89, 6, 60, 89, 8, 90, 45, 26, 23, 23, 56, 48, 12, 1, 0, 2, 562,
644 };
Mytree tree = new Mytree();
for (int i = 0; i < a.length; i++) {
if (i == 0) {
tree.setData(a[i]);
} else {
buderTree(tree, a[i]);
}
}
treePrint(tree);
}
/**
* 生成二叉树
*
* @param tree
* @param num
*/
private static void buderTree(Mytree tree, Integer num) {
if (num < tree.getData()) {
if (tree.getLeftTree() == null) {
Mytree tree_left = new Mytree();
tree_left.setData(num);
tree.setLeftTree(tree_left);
} else {
buderTree(tree.getLeftTree(), num);
}
} else {
if (tree.getRightTree() == null) {
Mytree tree_right = new Mytree();
tree_right.setData(num);
tree.setRightTree(tree_right);
} else {
buderTree(tree.getRightTree(), num);
}
}
}
/**
* 先序遍历输出二叉树
*
* @param tree
*/
private static void treePrint(Mytree tree) {
if (tree.getLeftTree() != null) {
treePrint(tree.getLeftTree());
}
System.out.println(tree.getData());
if (tree.getRightTree() != null) {
treePrint(tree.getRightTree());
}
}
/**
*
* @author 宋
*
*/
static class Mytree {
public Integer data;
private Mytree leftTree;
private Mytree rightTree;
public Mytree getLeftTree() {
return leftTree;
}
public void setLeftTree(Mytree leftTree) {
this.leftTree = leftTree;
}
public Mytree getRightTree() {
return rightTree;
}
public void setRightTree(Mytree rightTree) {
this.rightTree = rightTree;
}
public Integer getData() {
return data;
}
public void setData(Integer data) {
this.data = data;
}
}
}