二分法查找…查找…
代碼比較簡單…沒有註釋瞭
Java代碼
public class BinaryTree {
public static void main(String[] args) {
BinaryTree bt = new BinaryTree();
int[] ints = {12,123,21,123,1,432,23,42,3,123,124,3,5435,66,456554,435,423,42,1} ;
for (int i = 0; i <ints.length ; i++) {
bt.add(new Node(ints[i])) ;
}
bt.toPrint() ;
}
private Node root;
public void add(Node n) {
if(root==null){
root = n ;
return ;
}else{
add(root , n) ;
}
}
public void toPrint(){
toPrint(root) ;
}
private void toPrint(Node n){
if(n.getLeft()!=null){
toPrint(n.getLeft()) ;
}
System.out.println(n.getValue());
if(n.getRight()!=null){
toPrint(n.getRight()) ;
}
}
public void add(Node f , Node n){
if(f.getValue()==n.getValue()){
return ;
}
if(f.getValue()>n.getValue()){
if(f.getLeft()!=null){
add(f.getLeft(),n) ;
}else{
f.setLeft(n) ;
}
}else{
if(f.getRight()!=null){
add(f.getRight(),n) ;
}else{
f.setRight(n) ;
}
}
}
}
class Node {
public Node(int value) {
this.value = value;
}
private Node left;
private Node right;
private int value;
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
作者“ansjsun”