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).
题目意思:
给定一棵二叉搜索树,找到第k小的元素
注意:
1、利用二叉搜索树的特性
2、修改二叉搜索树的节点结构
3、最优时间复杂度是0(树的高度)
解题思路:
方法一:
二叉搜索树的特性:其中序遍历是有序的。故中序遍历访问,访问第k个元素即可。
方法二:
利用分冶的方法。
- 统计根节点左子树的节点个数cnt
- 如果cnt+1 = k,则根节点即为第k个最小元素
- 如果cnt+1 > k,则第k个最小元素在左子树,root = root->left;
- 如果cnt+1 < k,则第k个最小元素在右子树,root = root->right;
- 重复第一步
源代码:
方法一:
1 class Solution { 2 public: 3 int kthSmallest(TreeNode* root, int k) { 4 stack<TreeNode*> nodeStack; 5 if(root == NULL) return -1; 6 while(true){ 7 while(root){ 8 nodeStack.push(root); 9 root = root->left; 10 } 11 TreeNode* node = nodeStack.top(); nodeStack.pop(); 12 if(k == 1) return node->val; 13 else root = node->right,k--; 14 } 15 } 16 };
方法二:
1 class Solution { 2 public: 3 int calcNodeSize(TreeNode* root){ 4 if( root == NULL) return 0; 5 return 1 + calcNodeSize(root->left) + calcNodeSize(root->right); 6 } 7 8 int kthSmallest(TreeNode* root, int k) { 9 if(root == NULL) return 0; 10 int cnt = calcNodeSize(root->left); 11 if(k == cnt + 1) return root->val; 12 else if( k < cnt + 1 ) return kthSmallest(root->left,k); 13 else return kthSmallest(root->right, k-cnt-1); 14 } 15 };