首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。