Given the root of a binary search tree, and an integer k, return thek<sup>th</sup>smallest value (1-indexed) of all the values of the nodes in the 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
Constraints:
The number of nodes in the tree is n.
1 <= k <= n <= 10<sup>4</sup> 0 <= Node.val <= 10<sup>4</sup>
*Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
题目大意:
求BST的第k个最小元素(k从1开始)
算法思路:
N/A
注意事项:
用返回值(count, 结果). 递归右节点,用k - 1 - left_count
Line 9不能用if left_val,因为left_val可能是0,用is not None
Python代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
defkthSmallest(self, root: TreeNode, k: int) -> int: count, val = self.dfs(root, k) return val
defdfs(self, root, k): ifnot root: return0, None
left_count, left_val = self.dfs(root.left, k) if left_val isnotNone: # remember if left_val is wrong return0, left_val if left_count + 1 == k: return0, root.val right_count, right_val = self.dfs(root.right, k - left_count - 1) # remember k-1-left_count if right_val isnotNone: return0, right_val return left_count + 1 + right_count, right_val