Topic:
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:
- Try to utilize the property of a BST.
- What if you could modify the BST node ' s structure?
- The optimal runtime complexity is O (height of BST).
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Code:
/** Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: intKthsmallest (treenode* root,intk) {intCount =0; Stack<TreeNode*>STA; TreeNode* Curr =Root; while(!sta.empty () | |Curr) { if(Curr) {Sta.push (Curr); Curr= curr->Left ; } Else{Curr=Sta.top (); Sta.pop (); Count++; if(count==k)returnCurr->Val; Curr= curr->Right ; } } returnCurr->Val; }};
Tips
The intuitive approach is to traverse BST in the middle sequence and then get the K element.
"Kth smallest Element in a BST" CPP