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?
思路:
二叉搜索树的中序遍历(LNR)就是按照从小到大顺序排的,所以遍历到N节点的时候就记个数,计数到k的时候就返回了。
代码:
/** * 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: int kthSmallest(TreeNode* root, int k) { if(root == NULL) return -1; int retVal = -1; int count = 0; kthSmallest1(root, k, count, retVal); return retVal; } void kthSmallest1(TreeNode* root, int k, int& count, int& retVal){ if(count >= k) return; if(root->left != NULL) kthSmallest1(root->left, k, count, retVal); count ++; if(count == k){ retVal = root->val; return; } if(root->right != NULL) kthSmallest1(root->right, k, count, retVal); } };