二叉树
package datastructure;
public class BinaryTree<T> {
private Node root;
public Node getRoot() {
return root;
}
private class Node{
private T data;
private Node lift;
private Node right;
private Node(T a){
this.data = a;
}
}
private void addNode(Node node,T data){
if(((Comparable)data).compareTo(node.data) < 0){
if(node.lift == null){
node.lift = new Node(data);
}
addNode(node.lift,data);
}else if(((Comparable)data).compareTo(node.data) > 0){
if(node.right == null){
node.right = new Node(data);
}
addNode(node.right,data);
}
}
public void add(T data){
if(root == null){
root = new Node(data);
}else{
addNode(root,data);
}
}
public void inOrderTraversal(Node root){
if(root == null) return;
inOrderTraversal(root.lift);
System.out.println(root.data);
inOrderTraversal(root.right);
}
public void preOrderTraversal(Node root){
if(root == null) return;
System.out.println(root.data);
preOrderTraversal(root.lift);
preOrderTraversal(root.right);
}
public void lastOrderTraversal(Node root){
if(root == null) return;
lastOrderTraversal(root.lift);
lastOrderTraversal(root.right);
System.out.println(root.data);
}
}
package datastructure;
public class BinaryTreeTest {
public static void main(String[] args) {
BinaryTree<String> tree = new BinaryTree();
tree.add("kd");
tree.add("bull");
tree.add("ao");
tree.add("pp");
tree.add("sr");
tree.add("jame");
tree.add("qq");
tree.inOrderTraversal(tree.getRoot());
}
}
ao
bull
jame
kd
pp
qq
sr