二叉樹類:
package binarytreetraversal;
/**
*
* @author shootzp
*/
public class BST {
public static class BSTNode {
Comparable data;
BSTNode left;
BSTNode right;
public BSTNode() {
}
public BSTNode(Comparable obj) {
this.data = obj;
}
public BSTNode(Comparable obj, BSTNode leftChild, BSTNode rightChild) {
this.data = obj;
this.left = leftChild;
this.right = rightChild;
}
@Override
public String toString() {
return data.toString();
}
}
private BSTNode root;
private int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public BSTNode getRoot() {
return root;
}
public void setRoot(BSTNode root) {
this.root = root;
}
public BST() {
}
public void clear() {
root = null;
count = 0;
}
public void insert(Comparable val) {
root = insert(root, val);
}
// public void delete(Comparable val) {
// root = delete(root,val);
// }
public boolean isEmpty() {
return root == null;
}
public int size() {
return this.count + 1;
}
public boolean contains(Comparable val) {
return search(root, val) != null;
}
private BSTNode insert(BSTNode ref, Comparable val) {
if (ref == null) {
count++;
return new BSTNode(val);
} else {
int comp = val.compareTo(ref.data);
if (comp < 0) {
ref.left = insert(ref.left, val);
} else {
ref.right = insert(ref.right, val);
}
return ref;
}
}
// private BSTNode delete(BSTNode root, Comparable val) {
// throw new UnsupportedOperationException("Not yet implemented");
// }
private BSTNode search(BSTNode ref, Comparable val) {
if (ref == null) {
return null;
} else {
int comp = val.compareTo(ref.data);
if (comp == 0) {
return ref;
} else if (comp < 0) {
return search(ref.left, val);
} else {
return search(ref.right, val);
}
}
}
}
測試類:
package binarytreetraversal;
/**
*
* @author shootzp
*/
public class BSTTest {
public static void main(String[] args) {
BST b = new BST();
// BST.BSTNode root = new BSTNode("fox");
// b.setRoot(root);
b.insert("ant");
b.insert("cat");
b.insert("dog");
b.insert("fox");
b.insert("hen");
b.insert("pig");
b.insert("rat");
print(b);
}
public static void print2(BST.BSTNode ref, int level) {
if (ref == null) {
// System.out.println("空!");
return;
}
/* 逆中序遍歷二叉樹(右-根-左) */
print2(ref.right, level + 1); // 打印右子樹
for (int i = 0; i < level; i++) { //level控制打印層次縮進
System.out.print(" ");
}
System.out.println(ref.data); // 打印節點
print2(ref.left, level + 1); // 打印左子樹
}
public static void print(BST b) {
BST.BSTNode root = b.getRoot();
if (b.isEmpty()) {
return;
}
print2(root, 0);
}
}
結果:(試試改變插入順序查看結果)
rat
pig
hen
fox
dog
cat
ant