leetcode230---Kth Smallest Element in a BST(BST中寻找第K小)

问题描述:

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.

再BST中找出第k小的元素。

问题求解:

中序遍历,只遍历k个,时间复杂度O(k),空间复杂度O(1)。

/** * 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 {
    int count=0;
    int kthS;
public:
    int kthSmallest(TreeNode* root, int k) {
        InOrderBST(root, k);
        return kthS;
    }
    void InOrderBST(TreeNode* root, int k)
    {//利用BST中序遍历是有序序列,第k个即是所找
        if(root==NULL) return;
        InOrderBST(root->left, k);
        if(++count==k) 
        {
            kthS = root->val;
        }
        InOrderBST(root->right, k);
    }
};

优化:InOrderBST(root->right, k);前加上if(count < k),也就是当count=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 {
    int count=0;
    int kthS;
public:
    int kthSmallest(TreeNode* root, int k) {
        InOrderBST(root, k);
        return kthS;
    }
    void InOrderBST(TreeNode* root, int k)
    {//利用BST中序遍历是有序序列,第k个即是所找
        if(root==NULL) return;
        InOrderBST(root->left, k);
        if(++count==k) 
        {
            kthS = root->val;
        }
        //count=k时无需再遍历右子树
        if(count<k) InOrderBST(root->right, k);
    }
};

你可能感兴趣的:(LeetCode,BST)