LeetCode 230. Kth Smallest Element in a BST(寻找二叉查找树的第 k 个元素)

题意:寻找二叉查找树的第 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 ans = -1;
    int cnt = 0;
    int kthSmallest(TreeNode* root, int k) {
        inOrder(root, k);
        return ans;
    }
    void inOrder(TreeNode* root, int k){
        if(root == NULL) return;
        inOrder(root -> left, k);
        ++cnt;
        if(cnt == k){
            ans = root -> val;
            return;
        }
        inOrder(root -> right, 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) {
        int leftcnt = count(root -> left);
        if(leftcnt == k - 1) return root -> val;
        else if(leftcnt > k - 1) return kthSmallest(root -> left, k);
        else return kthSmallest(root -> right, k - leftcnt - 1);
    }
    int count(TreeNode* root){
        if(root == NULL) return 0;
        return count(root -> left) + count(root -> right) + 1;
    }
};

  

posted @ 2020-03-21 11:09  Somnuspoppy  阅读(134)  评论(0编辑  收藏  举报