Stay Hungry,Stay Foolish!

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

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

 https://leetcode.cn/problems/kth-smallest-element-in-a-bst/
 

思路

https://leetcode.cn/problems/kth-smallest-element-in-a-bst/solutions/1050055/er-cha-sou-suo-shu-zhong-di-kxiao-de-yua-8o07/
根据二叉搜索树性质,
对左子树进行搜索目标, 根节点判断, 然后对右子树进行目标搜索。
https://zhuanlan.zhihu.com/p/29867652

Code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    int count = 0;
public:
    int kthSmallest(TreeNode* root, int k) {
        return inorder(root, k);
    }
private:
    /*
    return kth value if found in this root, otherwise -1
    */
    int inorder(TreeNode* root, int k){
        if (root->left){
            int leftret = inorder(root->left, k);
            if (leftret != -1){
                return leftret;
            }
        }

        count++;
        if (count == k){
            return root->val;
        }

        if (root->right){
            int rightret = inorder(root->right, k);
            if (rightret != -1){
                return rightret;
            }
        }

        return -1;
    }
};

 

 
posted @ 2024-03-10 10:51  lightsong  阅读(1)  评论(0编辑  收藏  举报
Life Is Short, We Need Ship To Travel