No230. The Kth smallest element in the binary search tree
topic
Given a binary search tree, write a function kthSmallest
to 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
- Input: root = [3,1,4,null,2], k = 1
- Output: 1
Example 2
- 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 kthSmallest
function?
Ideas
- Using the idea of 215 questions, first traverse the data to fetch the data;
- 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