dfs
中序遍历即可
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
var num, ans int
var find bool
func kthSmallest(root *TreeNode, k int) int {
find = false
num, ans = 0, 0
dfs(root, k)
return ans
}
func dfs(root *TreeNode, k int) {
if find || root == nil {
return
}
if root.Left != nil {
dfs(root.Left, k)
}
num++
if num == k {
ans = root.Val
find = true
}
if root.Right != nil {
dfs(root.Right, k)
}
return
}
参考
230. 二叉搜索树中第K小的元素 - 力扣(Leetcode)
题解中有后续优化的解法
题解-230. 二叉搜索树中第K小的元素 - 力扣(Leetcode)
标签:TreeNode,int,230,dfs,num,ans,root,树中,leetcode From: https://www.cnblogs.com/wudanyang/p/17035453.html