530. Minimum Absolute Difference in BST #
Problem #
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example:
Input:
1
\
3
/
2
Output:
1
Explanation:
The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
Note:
- There are at least two nodes in this BST.
- This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/
Problem Summary #
Given a binary search tree with all nodes having non-negative values, calculate the minimum absolute difference between the values of any two nodes in the tree.
Solution Ideas #
- Since it is a BST, use its ordered property: the result of an inorder traversal is sorted. During the inorder traversal, dynamically maintain the difference between the previous and current nodes to find the minimum difference.
- This problem is exactly the same as Problem 783.
Code #
package leetcode
import (
"math"
"github.com/halfrost/leetcode-go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func getMinimumDifference(root *TreeNode) int {
res, nodes := math.MaxInt16, -1
dfsBST(root, &res, &nodes)
return res
}
func dfsBST(root *TreeNode, res, pre *int) {
if root == nil {
return
}
dfsBST(root.Left, res, pre)
if *pre != -1 {
*res = min(*res, abs(root.Val-*pre))
}
*pre = root.Val
dfsBST(root.Right, res, pre)
}
func min(a, b int) int {
if a > b {
return b
}
return a
}
func abs(a int) int {
if a > 0 {
return a
}
return -a
}