230. 二叉搜索树中第K小的元素(中等,树)

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

说明:
你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。

示例 1:

输入: root = [3,1,4,null,2], k = 1
   3
  / \
 1   4
  \
   2
输出: 1

思路:首先注意搜索二叉树的特点,左子树、根结点、右子树一次增大,所以和中序遍历刚好结合在一次。

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

class Solution:
    def kthSmallest(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: int
        """
        #中序遍历
        def dummy(root,l):
            if not root:
                return 
            if root.left:
                dummy(root.left,result)
            result.append(root.val)
            if root.right:
                dummy(root.right,result)
        result=[]
        dummy(root,result)
        return result[k-1]

执行用时: 84 ms, 在Kth Smallest Element in a BST的Python3提交中击败了81.11% 的用户

猜你喜欢

转载自blog.csdn.net/weixin_42234472/article/details/84931703