給定一個二叉搜索樹,編寫一個函數 kthSmallest 來查找其中第 k 個最小的元素。
說明:
你可以假設 k 總是有效的,1 ≤ k ≤ 二叉搜索樹元素個數。
示例 1:
輸入: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
輸出: 1
示例 2:
輸入: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
輸出: 3
進階:
如果二叉搜索樹經常被修改(插入/刪除操作)並且你需要頻繁地查找第 k 小的值,你將如何優化 kthSmallest 函數?
---------------------
作者:Mr_Curious_
來源:CSDN
原文:https://blog.csdn.net/xuchonghao/article/details/80770490
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!
golang語言使用中序遍歷,使用棧
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func kthSmallest(root *TreeNode, k int) int {
//中序遍歷
if root==nil || k<=0{
return -1
}
s:=NewStack()
GetBTVal(root ,s )
fmt.Println(s.Val)
for index,v:=range s.Val{
if index+1==k{
return v
}
}
return -1
}
type Stack struct{
Val []int
Top int
}
func NewStack()*Stack{
return &Stack{Val:make([]int,0),Top:0}
}
func (s *Stack)Push(v int){
s.Val=append(s.Val,v)
}
func (s *Stack)Pop()int{
if s.Top==0{
return -1
}
v:=s.Val[s.Top-1]
s.Top--
return v
}
func (s *Stack)IsEmpty()bool{
if s.Top==0{
return true
}
return false
}
func GetBTVal(root *TreeNode,s *Stack){
if root==nil{
return
}
GetBTVal(root.Left,s)
s.Val =append(s.Val,root.Val)
GetBTVal(root.Right,s)
}