题解 | #第k轻的牛牛#
第k轻的牛牛
https://www.nowcoder.com/practice/d3b31f055b1640d9b10de0a6f2b8e6f3?tpId=354&tqId=10591747&ru=/exam/oj/ta&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D354
知识点:
二叉搜索树的中序遍历
解题思路:
二次搜索树的中序遍历是一个递增序列,我们只需要在中序位置判断当前节点是否是第k个即可。
语言:
Golang
package main
import . "nc_tools"
/*
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param k int整型
* @return int整型
*/
func kthLighest( root *TreeNode , k int ) int {
// write code here
ans:=0
count:=0
var dfs func(root *TreeNode,k int)
dfs=func(root *TreeNode,k int){
if root == nil{
return
}
dfs(root.Left,k)
count++
if count == k{
ans = root.Val
return
}
dfs(root.Right,k)
}
dfs(root,k)
return ans
}
