/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */import"math"funcgetMinimumDifference(root *TreeNode) int { result, previous := math.MaxInt16, -1getMinDiffHelper(root, &result, &previous)return result}funcgetMinDiffHelper(root *TreeNode, res, prev *int) {if root ==nil {return }getMinDiffHelper(root.Left, res, prev)if*prev !=-1 {*res =min(*res, abs(root.Val -*prev)) }*prev = root.ValgetMinDiffHelper(root.Right, res, prev)}funcmin(x, y int) int {if x > y {return y }return x}funcabs(x int) int {if x >=0 {return x }return-x}
Keep track of the previous node. Similar to an inorder traversal.