Total Accepted: 28176 Total Submissions: 82688 Difficulty: Medium
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?
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void inorder(TreeNode* root, int &k,int &val){ if(!root) return; inorder(root->left,k,val); if(--k == 0){ val = root->val; return; } inorder(root->right,k,val); } int kthSmallest(TreeNode* root, int k) { int res = 0; inorder(root,k,res); return res; } };