标签:有序 onclick elf pre event HERE amp play root
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.
Example 1:
Input: root = [3,1,4,null,2], k = 1 3 / 1 4 2 Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3 5 / 3 6 / 2 4 / 1 Output: 3
Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?
1 # Definition for a binary tree node. 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution: 9 def kthSmallest1(self, root: TreeNode, k: int) -> int: 10 def inorder(r): 11 return inorder(r.left) + [r.val] + inorder(r.right) if r else [] # pythonic style 12 13 return inorder(root)[k - 1] 14 15 def kthSmallest(self, root: TreeNode, k: int) -> int: 16 stack = [] 17 18 while True: 19 while root: 20 stack.append(root) 21 root = root.left 22 23 root = stack.pop() 24 k -= 1 25 26 if not k: 27 return root.val 28 29 root = root.right
Leetcode 230. Kth Smallest Element in a BST
标签:有序 onclick elf pre event HERE amp play root
原文地址:https://www.cnblogs.com/pegasus923/p/11266173.html