public class Node {
protected Comparable data;//根
protected Node left;// 左节点
protected Node right;// 右节点
// 加入节点
protected void addNode(Node newData) {
if (newData.data.compareTo(this.data) < 0) {
if (this.left == null) {
this.left = newData;
} else {
this.left.addNode(newData);
}
}
if (newData.data.compareTo(this.data) >= 0) {
if (this.right == null) {
this.right = newData;
} else {
this.right.addNode(newData);
}
}
}
}
-----------------------------------------------------------------------
class BinaryTree {
public Node root;//顶级根节点
public void add(Comparable data){
Node newNode = new Node();
newNode.data = data;
if(root == null){
root = newNode;
}else{
root.addNode(newNode);
}
}
public void printNode(Node node){
if(node.left!=null){
printNode(node.left);
}
if(node.right != null){
printNode(node.right);
}
}
}
public class CompareDemo{
public static void main(String[] args) {
BinaryTree binaryTree = new BinaryTree();
for(int i = 0;i<100000;i++){
binaryTree.add(Math.random()*100);
}
long temp = System.currentTimeMillis();
binaryTree.printNode(binaryTree.root);
System.out.println(System.currentTimeMillis()-temp);
}
}