Kth smallest Element in a BST solution

Source: Internet
Author: User

Question

Given A binary search tree, write a function to kthSmallest find the kth smallest element in it.

Note:
You may assume k are always valid, 1≤k≤bst's total elements.

Follow up

What if the BST are modified (Insert/delete operations) often and you need to find the kth smallest frequently? How would optimize the Kthsmallest routine?

Hint:

    1. Try to utilize the property of a BST.
    2. What if you could modify the BST node ' s structure?
    3. The optimal runtime complexity is O (height of BST).
Solution 1--inorder traversal

Again, we use the feature of inorder traversal of BST. But this solution was not the best for follow up. Time complexity O (n), n is the number of nodes.

1 /**2 * Definition for a binary tree node.3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8  * }9  */Ten  Public classSolution { One      Public intKthsmallest (TreeNode root,intk) { ATreeNode current =Root; -stack<treenode> stack =NewStack<treenode>(); -          while(Current! =NULL|| !Stack.empty ()) { the             if(Current! =NULL) { - Stack.push (current); -Current =Current.left; -}Else { +TreeNode tmp =Stack.pop (); -k--; +                 if(k = = 0) { A                     returnTmp.val; at                 } -Current =Tmp.right; -             } -         } -         return-1; -     } in}
Solution 2--augmented Tree

The idea was to maintain rank of each node. We can keep track of elements in a subtree of any node while building the tree. Since we need k-th smallest element, we can maintain number of elements of left subtree in every node.

Assume the root is has N nodes in it left subtree. If K = N + 1, Root is k-th node. If K < N, we'll continue our search (recursion) for the Kth smallest element with the left subtree of root. If K > N + 1, we continue our search on the right subtree for the (k–n–1)-th smallest element. Note that we need the count of elements in to subtree only.

Time Complexity:o (h) where h is height of tree.

(Referrence:geeksforgeeks)

Here, we construct the tree in a-taught during algorithm class.

"size" is a attribute which indicates number of nodes in sub-tree rooted in that node.

Time complexity:constructing tree O (n), find Kth Smallest number O (h).

Start:if k = root.leftelement + 1   root node is the K th node.   Goto Stopelse If k > root.leftelements   k = k-(root.leftelements + 1)   root = root.right   goto startelse
   
    root = root.left   goto srartstop
   
1 /**2 * Definition for a binary tree node.3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8  * }9  */Ten classImprovedtreenode { One     intVal; A     intSize//Number of nodes in the subtree so rooted in this node - Improvedtreenode left; - Improvedtreenode right; the      PublicImprovedtreenode (intValue) {val =value;} - } -  -  Public classSolution { +      -     //Construct Improvedtree recursively +      PublicImprovedtreenode createaugmentedbst (TreeNode root) { A         if(Root = =NULL) at             return NULL; -Improvedtreenode Newhead =NewImprovedtreenode (root.val); -Improvedtreenode left =Createaugmentedbst (root.left); -Improvedtreenode right =Createaugmentedbst (root.right); -Newhead.size = 1; -         if(Left! =NULL) inNewhead.size + =left.size; -         if(Right! =NULL) toNewhead.size + =right.size; +Newhead.left =Left ; -Newhead.right =Right ; the         returnNewhead; *     } $     Panax Notoginseng      Public intFindkthsmallest (Improvedtreenode root,intk) { -         if(Root = =NULL) the             return-1; +Improvedtreenode tmp =Root; A         intLeftsize = 0; the         if(Tmp.left! =NULL) +Leftsize =tmp.left.size; -         if(leftsize + 1 = =k) $             returnRoot.val; $         Else if(Leftsize + 1 >k) -             returnFindkthsmallest (Root.left, k); -         Else the             returnFindkthsmallest (Root.right, k-leftsize-1); -     }Wuyi      the      Public intKthsmallest (TreeNode root,intk) { -         if(Root = =NULL) Wu             return-1; -Improvedtreenode Newroot =Createaugmentedbst (root); About         returnFindkthsmallest (Newroot, k); $     } -}

Kth smallest Element in a BST solution

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.