[Leetcode] 230. Kth Smallest Element in a BST

No230. The Kth smallest element in the binary search tree

topic

Given a binary search tree, write a function kthSmallestto find which k-th smallest element.

Description

You can assume that k is always valid, and 1 ≤ k ≤ the number of elements in the binary search tree.

Example 1

Insert picture description here

  • Input: root = [3,1,4,null,2], k = 1
  • Output: 1

Example 2

Insert picture description here

  • Input: root = [5,3,6,2,4,null,null,1], k = 3
  • Output: 3

Advanced

If the binary search tree is often modified (insertion / deletion) and you need to find the smallest value k frequently, you will how to optimize kthSmallestfunction?

Ideas

  1. Using the idea of ​​215 questions, first traverse the data to fetch the data;
  2. The fetched data is in ascending order and can be accessed directly by indexing;

Problem-solving code (Python3)

# 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 __init__(self):
        self.nums = []
    def kthSmallest(self, root: TreeNode, k: int) -> int:
        #前序遍历
        def preOrder(node):
            if node:
                preOrder(node.left)
                self.nums.append(node.val)
                preOrder(node.right)
        preOrder(root)
        return self.nums[k-1]

Complexity analysis:

  • Time complexity O(n)
  • Space complexity O(n) requires additional space to store node values

operation result

Insert picture description here

Guess you like

Origin blog.csdn.net/Xiao_Spring/article/details/113776098