Leetcode Note: Go - Minimum Absolute Difference in BST

Minimum Absolute Difference in BST - LeetCode
https://leetcode.com/problems/minimum-absolute-difference-in-bst/

  • Go 言語で取り組んだメモ

所感

  • BST: Binary Search Tree のノードで最も低い絶対値を int で return する

回答

[Go] Solution - LeetCode Discuss
https://leetcode.com/problems/minimum-absolute-difference-in-bst/discuss/556068/Go-Solution

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func getMinimumDifference(root *TreeNode) int {
    min := math.MaxInt64
    preVal := math.MinInt32
    
    helper := func(n *TreeNode){}
    helper = func(n *TreeNode){
        if n == nil{
            return
        }
        
        helper(n.Left)
        if preVal != math.MinInt32{
            d := n.Val - preVal
            if d < min {
                min = d
            }
        }
        
        preVal = n.Val
        helper(n.Right)
    }
    
    helper(root)
    return min
}
  • helper 変数に anonymous function を定義して再帰