
二叉搜索树的中序遍历就是升序排序
package mainimport "fmt"type TreeNode struct {Val intLeft *TreeNodeRight *TreeNode}// 中序遍历func kthSmallest(root *TreeNode, k int) int {if root==nil{return 0}stack := make([]*TreeNode,0)i :=0for root!=nil||len(stack)>0{if root!= nil {stack = append(stack,root)root = root.Left}else {curr :=stack[len(stack)-1]stack = stack[:len(stack)-1]// 数据出站if i==k-1 {return curr.Val}i++root = curr.Right}}return 0}func main() {a := &TreeNode{Val: 3,}b := &TreeNode{Val: 1,}a.Left = bc := &TreeNode{Val: 4,}a.Right = cd := &TreeNode{Val: 2,}b.Right = dfmt.Println(kthSmallest(a,1))}

递归
func kthSmallest1(root *TreeNode, k int) int{index = kdfs(root)return res}var res intvar index intfunc dfs(root *TreeNode){if root==nil {return}dfs(root.Left)if index==0 {res = root.Valreturn}dfs(root.Right)}
