leetcode 230 二叉搜索树中第K小的元素

时间:2022-08-07 20:39:43

方法1:统计每个节点的子节点数目,当k>左子树节点数目时向左子树搜索,k=左子树节点数目时返回根节点,否则向右子树搜索。

方法2:递归中序遍历,这里开了O(n)空间的数组。

class Solution {
public:
vector<int> result;//中序遍历序列
void myInorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
//先遍历左子树
if (root->left != NULL) {
myInorderTraversal(root->left);
}
//遍历当前根节点
result.push_back(root->val);
//再遍历右子树
if (root->right != NULL) {
myInorderTraversal(root->right);
}
}
int kthSmallest(TreeNode* root, int k) {
myInorderTraversal(root);//中序遍历二叉搜索树
return result[k - ];
}
};

方法3:非递归中序遍历

class Solution {
public:
int kthSmallest(TreeNode *root, int k)
{
stack<TreeNode *> s;
while ()
{
if (root)
{
s.push(root);
root = root->left;
continue;
}
if (k == )
return s.top()->val;
root = s.top()->right;
s.pop();
k--;
}
}
};