LeetCode 230. Kth Smallest Element in a BST 解题报告(python)

230. Kth Smallest Element in a BST

  1. Kth Smallest Element in a BST python solution

题目描述

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note:
You may assume k is always valid, 1 ≤ k ≤ BST’s total elements.
在这里插入图片描述

解析

因为是二叉搜索树,那么节点值的大小已经排好序了,左子树小于根节点小于右子树。所以我们只需进行一次DFS,将所有节点的值记录下来,这些节点值已经排好序了,我们只需要输出第k个即可。

class Solution:
    def kthSmallest(self, root: TreeNode, k: int) -> int:
        count=[]
        self.helper(root,count)
        return count[k-1]
    
    def helper(self,node,count):
        if not node:
            return 
        self.helper(node.left,count)
        count.append(node.val)
        self.helper(node.right,count)
        

Reference

https://leetcode.com/problems/kth-smallest-element-in-a-bst/discuss/63660/3-ways-implemented-in-JAVA-(Python)%3A-Binary-Search-in-order-iterative-and-recursive

发布了131 篇原创文章 · 获赞 6 · 访问量 6919

猜你喜欢

转载自blog.csdn.net/Orientliu96/article/details/104391012