BST Insert
package BinarySearchTree;
//创建一个Node类
class Node{
int value;
Node left;
Node right;
public Node(int value){
this.value=value;
left=null;
right=null;
}
}
class BinarySearchTree {
Node root;
public BinarySearchTree() {
root = null;
}
private Node insertRec(Node root,int value){
if(root==null) {
root = new Node(value); //!!!
return root;//!!!
}
if(value< root.value){
root.left=insertRec(root.left,value);//!!!
} else if (value> root.value) {
root.right=insertRec(root.right,value);//!!!
}
return root;
}
//封装性
public void insert(int value){
root=insertRec(root,value);
}
}
public class BinarySTInsert {
public static void main(String[] args) {
BinarySearchTree T = new BinarySearchTree();
T.insert(20);
T.insert(30);
T.insert(10);
T.insert(90);
T.insert(35);
T.insert(70);
T.insert(60);
inoderdertraversal(T.root);
}
public static void inoderdertraversal (Node root){//!!!自己敲的时候把该方法写在了psvm里
if (root != null) {
inoderdertraversal(root.left);
System.out.print(root.value + " ");
inoderdertraversal(root.right);
}
}
}
或者改成public static void main(String[] args) {
private static void inoderdertraversal (Node root){}
}