530.二叉搜索树的最小绝对差

87 阅读1分钟

题目:
给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。

差值是一个正数,其数值等于两值之差的绝对值。
算法:
1.用到了bst中序遍历时升序的特征,最小差值肯定是相邻数的差值。
2.preVal >= 0时可以计算差值。

func getMinimumDifference(root *TreeNode) int {
	ans := math.MaxInt32
	preVal := -1
	var dfs func(node *TreeNode) 
	dfs = func(node *TreeNode){
		if node == nil {
			return
		}
		dfs(node.Left)
		if preVal >= 0 {
			curDiff :=  node.Val - preVal
			if curDiff < ans {
				ans = curDiff
			}
		}
		preVal = node.Val
		dfs(node.Right)

	}
	dfs(root)

	return ans
}