码迷,mamicode.com
首页 > 其他好文 > 详细

BST(Binary Search Tree)

时间:2014-07-22 23:06:34      阅读:330      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   java   color   

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

mamicode.com,码迷
 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     }
mamicode.com,码迷
mamicode.com,码迷
 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     }
mamicode.com,码迷

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

 

BST(Binary Search Tree),码迷,mamicode.com

BST(Binary Search Tree)

标签:des   style   blog   http   java   color   

原文地址:http://www.cnblogs.com/Altaszzz/p/3700542.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!