题解 | #二叉搜索树最小差值# | Golang
二叉搜索树最小差值
https://www.nowcoder.com/practice/f8ac976b49bd450887b9281f315186c7
package main import ( "math" . "nc_tools" ) /* * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型 */ func minDifference( root *TreeNode ) int { pre_val := -1 ans := math.MaxInt minOrder(root, &pre_val, &ans) return ans } func minOrder(node *TreeNode, pre_val *int, ans *int) { if node == nil { return } minOrder(node.Left, pre_val, ans) if *pre_val != -1 { *ans = min(*ans, node.Val - *pre_val) } *pre_val = node.Val minOrder(node.Right, pre_val, ans) } func abs(a int) int { if a < 0 { return -a } return a } func min(a int, b int) int { if a < b { return a } return b }