package tree;
/**
* 排序树
*
* @author Administrator
*
*/
public class SortedTree {
private Node root;
public void insert(int i) {
Node newNode = new Node(i);
// 第一次插入
if (root == null) {
root = newNode;
} else {
Node current = root;
Node father = null;
while (current != null) {
father = current;
if (current.value >= i) {// 添加到左节点
current = current.left;
} else {// 添加到右节点
current = current.right;
}
}
// 插入数据
if (father.value >= i) {// 添加到左节点
father.left = newNode;
} else {// 添加到右节点
father.right = newNode;
}
}
}
/**
* 中根遍历
*/
public void midOrder() {
doMidOrder(root);
}
private void doMidOrder(Node node) {
// 先遍历左子树
if (node.left != null) {
doMidOrder(node.left);
}
// 再遍历根节点
System.out.print(node.value + " ");
// 最后遍历右子树
if (node.right != null) {
doMidOrder(node.right);
}
}
/**
* 后根遍历
*/
public void lastOrder() {
doLastOrder(root);
}
private void doLastOrder(Node node) {
// 先遍历左子树
if (node.left != null) {
doLastOrder(node.left);
}
// 再遍历右子树
if (node.right != null) {
doLastOrder(node.right);
}
// 最后遍历根节点
System.out.print(node.value + " ");
}
private class Node {
Node left;// 左儿子
int value;// 节点值
Node right;// 右儿子
int layerNo;// 层数
private Node(int value) {
this.value = value;
}
}
}