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 _get_in_order_list(TreeNode* root, vector<int> &in_list) { if (NULL == root) { return; } _get_in_order_list(root->left, in_list); in_list.push_back(root->val); _get_in_order_list(root->right, in_list); } int kthSmallest(TreeNode* root, int k) { vector<int> in_list; _get_in_order_list(root, in_list); return in_list[k - 1]; } };