Given a binary search tree, write a function kthSmallest
to find the kth smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you 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.
analysis:
Method a: preorder directly to the k +;
Option two: frame traversal sequence, upon detection of the k-th, return directly to save some space complexity.
Inorder traversal of the code
class Solution { public: vector<int> preorderTraversal(TreeNode *root) { vector<int> result; stack<TreeNode*> stack; TreeNode *p = root; while( NULL != p || !stack.empty()) { while(NULL != p) { result.push_back(p->val); stack.push(p); p = p->left; } if(!stack.empty()) { p= stack.top(); stack.pop(); p=p->right; } } return result; } };
Improved use preorder to resolve the issue of code:
class Solution { public: int kthSmallest(TreeNode* root, int k) { stack<TreeNode*> st; TreeNode* p = root; int cnt = 0; while(p != NULL || !st.empty()) { while(p) { st.push(p); p = p->left; } if(!st.empty()) { p = st.top(); st.pop(); cnt ++; if(cnt == k) { return p->val; } p = p->right; } } return -1; } };
Reproduced in: https: //www.cnblogs.com/diegodu/p/4624497.html