Leetcode Note: Go - Minimum Distance Between BST Nodes
Minimum Distance Between BST Nodes - LeetCode
https://leetcode.com/problems/minimum-distance-between-bst-nodes/
- Go 言語で取り組んだメモ
所感
- BST: Binary Search Tree から Node を比較していき、最も小さい値を return する
回答
[GO] In-Order Traversal Solution - LeetCode Discuss
https://leetcode.com/problems/minimum-distance-between-bst-nodes/discuss/559488/GO-In-Order-Traversal-Solution
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func minDiffInBST(root *TreeNode) int {
min := math.MaxInt32
prevVal := math.MinInt32
helper := func(node *TreeNode) {}
helper = func(n *TreeNode){
if n == nil {
return
}
helper(n.Left)
if prevVal != math.MinInt32{
d := n.Val - prevVal
if d < min{
min = d
}
}
prevVal = n.Val
helper(n.Right)
}
helper(root)
return min
}