[Leetcode230]二叉搜索树中第K小的元素

给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。

还是那句话,树,优先考虑递归。

python:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def kthSmallest(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: int
        """
        if root == None:
            return None
        lsize = self.count(root.left)
        if lsize + 1 == k:
            return root.val
        elif lsize + 1 < k:
            return self.kthSmallest(root.right,k - lsize - 1)
        else:
            return self.kthSmallest(root.left,k)
    def count(self,root):
        if root == None:
            return 0
        return 1 + self.count(root.left) + self.count(root.right)

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) {
        if(root == NULL) return NULL;
        int lsize = count(root->left);
        if(lsize + 1 == k) return root->val;
        else if(lsize + 1 < k){
            return kthSmallest(root->right,k - lsize -1);
        }
        else{
            return kthSmallest(root->left,k);
        }
    }
    
    int count(TreeNode* root){
        if(root == NULL) return 0;
        return 1 + count(root->left) + count(root->right);
    }
};

猜你喜欢

转载自blog.csdn.net/qq_40501689/article/details/83056955