Skip to content

Commit 779d046

Browse files
committed
solved: 783. Minimum Distance Between BST Nodes
Signed-off-by: rajput-hemant <[email protected]>
1 parent 2475677 commit 779d046

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package main
2+
3+
import "math"
4+
5+
// Definition for a binary tree node.
6+
type TreeNode struct {
7+
Val int
8+
Left *TreeNode
9+
Right *TreeNode
10+
}
11+
12+
func minDiffInBST(root *TreeNode) int {
13+
var (
14+
minDiff = math.MaxInt
15+
prev = -1
16+
)
17+
18+
var dfs func(*TreeNode)
19+
dfs = func(node *TreeNode) {
20+
if node == nil {
21+
return
22+
}
23+
24+
dfs(node.Left)
25+
26+
if prev != -1 {
27+
minDiff = int(math.Min(float64(minDiff), float64(node.Val-prev)))
28+
}
29+
prev = node.Val
30+
31+
dfs(node.Right)
32+
}
33+
34+
dfs(root)
35+
36+
return minDiff
37+
}

0 commit comments

Comments
 (0)