publicintgetMinimumDifference(TreeNode root) { ans = Integer.MAX_VALUE; pre = -1; dfs(root); return ans; }
publicvoiddfs(TreeNode root) { if (root == null) { return; } dfs(root.left); if (pre == -1) { pre = root.val; } else { ans = Math.min(ans, root.val - pre); pre = root.val; } dfs(root.right); } }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
var getMinimumDifference = function(root) { let ans = Number.MAX_SAFE_INTEGER, pre = -1; constdfs = (root) => { if (root === null) { return; } dfs(root.left); if (pre == -1) { pre = root.val; } else { ans = Math.min(ans, root.val - pre); pre = root.val; } dfs(root.right); } dfs(root); return ans; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
funcgetMinimumDifference(root *TreeNode)int { ans, pre := math.MaxInt64, -1 var dfs func(*TreeNode) dfs = func(node *TreeNode) { if node == nil { return } dfs(node.Left) if pre != -1 && node.Val-pre < ans { ans = node.Val - pre } pre = node.Val dfs(node.Right) } dfs(root) return ans }