【leetcode】230: 二叉搜索树中第K小的元素

 

 这个题目利用二叉搜索树的性质,一下子就简单得令人发指了,第k小的元素,正好就是对二叉搜索树进行中序遍历时的第k个元素,因此我们直接使用中序遍历,时间复杂度O(n),即可得到答案,代码如下:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
        ls=[]
        def DFS(root,ls):
            if root==None:
                return 
            DFS(root.left,ls)
            ls.append(root.val)
            DFS(root.right,ls)
        
        DFS(root,ls)
        return ls[k-1]

得解!

posted @ 2021-10-14 21:39  Geeksongs  阅读(6)  评论(0编辑  收藏  举报

Coded by Geeksongs on Linux

All rights reserved, no one is allowed to pirate or use the document for other purposes.