1234567891011121314151617181920212223242526272829303132333435363738394041 |
- var pre int = 0
- var ini bool = false
- /**
- * Definition for a binary tree node.
- * type TreeNode struct {
- * Val int
- * Left *TreeNode
- * Right *TreeNode
- * }
- */
- func getMinimumDifference(root *TreeNode) (diff int) {
- pre, diff = 0, 1<<32-1
- ini = false
- inorder(root, &diff)
- return
- }
- func inorder(root *TreeNode, diff *int) {
- if root == nil {
- return
- }
- inorder(root.Left, diff)
- if ini {
- d := abs(root.Val - pre)
- if d < *diff {
- *diff = d
- }
- } else {
- ini = true
- }
- pre = root.Val
- inorder(root.Right, diff)
- }
- func abs(x int) int {
- if x < 0 {
- return -x
- }
- return x
- }
|