LeetCode--230. Kth Smallest Element in a BST(二叉搜索树中的第k个数)

题目:给定一个二叉搜索树和一个整数k,返回二叉搜索树中的第k个值。

解题思路:直接中序遍历二叉搜索树,则会返回一个有序数组,直接返回该数组的第k个值即可。

代码:

# 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
        """
        List = []
        def Iteration(root,List):
            if root:
                List = Iteration(root.left,List)
                List.append(root.val)
                List = Iteration(root.right,List)
                return List
            else:
                return List
        List = Iteration(root,List)
        return List[k-1]

猜你喜欢

转载自blog.csdn.net/xiaoxiaoley/article/details/80318622