给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k 个最小元素(从 1 开始计数)。
示例 1:
输入:root = [3,1,4,null,2], k = 1
输出:1
示例 2:
输入:root = [5,3,6,2,4,null,null,1], k = 3
输出:3
提示:
树中的节点数为 n 。
1 <= k <= n <= 10的4次方
0 <= Node.val <= 10的4次方
进阶:如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化算法?
这次用go写了一下。
package _0211017
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func kthArray(root *TreeNode, k int, arr *[]int) {
if(root.Left!=nil){
kthArray(root.Left, k, arr)
}
if(root!=nil && k!=0){
*arr = append(*arr, root.Val)
k--
}
if(root.Right!=nil) {
kthArray(root.Right, k, arr)
}
}
func kthSmallest(root *TreeNode, k int) int {
var dynaArr[] int
kthArray(root, k, &dynaArr)
return dynaArr[k-1]
}