Problem:
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.https://leetcode.com/problems/kth-smallest-element-in-a-bst/
Thinking:
The kth smallest node is the left child's left child...(all the way to leaf node) of the right child of the (k - 1) th node in a binary search tree.C++ Code:(脑洞:刚开始写C++,代码风格好像怪怪的)
/**
* 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) {
stack<TreeNode*> nodes;
if(root == NULL) return -1;
while(true){
while(root!=NULL){
nodes.push(root);
root=root->left;
}
TreeNode* node=nodes.top();
nodes.pop();
if(k==1) return node->val;
else {
root=node->right;
k--;
}
}
}
};
Java Code (Using Divide and Conquer):
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int kthSmallest(TreeNode root, int k) {
int leftCount = countNodes(root.left) + 1;
if (leftCount == k) {
return root.val;
} else if (leftCount > k) {
return kthSmallest(root.left, k);
} else {
return kthSmallest(root.right, k - leftCount);
}
}
private int countNodes(TreeNode root) {
if (root == null) {
return 0;
}
return countNodes(root.left) + countNodes(root.right) + 1;
}
}
这题用分治不需要额外空间
回复删除多谢提醒,分治的Java版代码已加上
删除此评论已被作者删除。
回复删除class Solution {
回复删除public:
int kthSmallest(TreeNode* root, int k) {
if(data.size()==k)
return data[k-1];
if (root->left!=nullptr)
kthSmallest(root->left,k);
data.push_back(root->val);
if (root->right!=nullptr)
kthSmallest(root->right,k);
return data[k-1];
}
private:
vector data;
};
提供一个我觉得超级蠢逼的做法.....直接遍历,反正遍历出来的顺序就是从最小到最大,而且不需要遍历完,中途返回就OK了,,,不知道有没有问题,反正leetcode 很多测试不全orz
很好啊!感谢感谢!学习了!🙏
删除