首页 > 代码库 > BST(Binary Search Tree)

BST(Binary Search Tree)

Definition: see wiki http://en.wikipedia.org/wiki/Binary_search_tree

 1 /*
 2     This look up is a fast operation because you eliminate the half
 3     the nodes from your search on each iteration by choose to follow the
 4     left or right of the sub-tree. In the worst case, you will know whether
 5     the lookup was successful by the time there is only one node left to
 6     search. Therefore, the running time of the lookup is equal to the number
 7     of times that you can halve n nodes before you get to 1. This number, x,
 8     is the same as the number of times you can double 1 before reach n, and it can
 9     be expressed as 2^x = n. You can find x using logarithm. So the Time complexity
10     if Theta(log(n))
11      */
12     public TreeNode lookUp(TreeNode root, int val){
13     //Note: this method only applies to BST(Binary search tree)
14         while(root!=null){
15             int cur_val = root.val;
16             if(val == cur_val)
17                 break;
18             if(cur_val<val)
19                 root = root.left;
20             else // cur_val > val, we search for the
21                 root = root.right;
22         }
23         return root;
24     }
 1     //Recursion version of the look_up 
 2     public TreeNode lookUp_recursion(TreeNode root, int val){
 3         if(root == null)
 4             return null;
 5         int current_val = root.val;
 6         if(current_val == val)
 7                 return root;
 8         if(current_val<val)
 9             return lookUp_recursion(root.left,val);
10         else
11             return lookUp_recursion(root.right,val);
12     }

Deletion and Insertion

  Without goint into too much detail(as the special cases get very nasty), it is also possible to delete and insert into a balanced BST in log(n)

Other Important Properties

  Smallest element: It‘s possible to obtain the smallest element by following all the left children.

  Largest element: To obtain the largest element, we could follow all the right children