题解 | #牛群最小体重差#
牛群最小体重差
https://www.nowcoder.com/practice/e96bd1aad52a468d9bff3271783349c1?tpId=354&tqId=10591744&ru=/exam/oj/ta&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D354
知识点:
二叉搜索树的中序遍历
解题思路:
二叉搜索树的中序遍历就是一个递增的序列,每次在中序的时候计算一边差值即可
语言:
Golang
package main
import (
"math"
)
/*
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
func getMinimumDifference( root *TreeNode ) int {
// write code here
res:=math.MaxInt32
pre:=math.MinInt32
var dfs func(root *TreeNode)
dfs = func(root *TreeNode) {
if root == nil{
return
}
dfs(root.Left)
if root.Val - pre < res{
res = root.Val-pre
}
pre = root.Val
dfs(root.Right)
}
dfs(root)
return res
}
