LeetCode 530. 二叉搜索树的最小绝对差Golang版
1. 问题描述
给你一棵所有节点为非负值的二叉搜索树,请你计算树中任意两节点的差的绝对值的最小值。
2. 思路
2.1. 递归
遇到了一个问题,*int可以模拟全局变量,*TreeNode没法模拟全局变量效果
问题如下
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func getMinimumDifference(root *TreeNode) int {
var prev TreeNode
res := math.MaxInt64
dfs(root, &prev, &res)
return res
}
func dfs(root *TreeNode, prev *TreeNode, res *int) {
if root == nil {
return
}
dfs(root.Left, prev, res)
// if prev != nil {
// if root.Val - prev.Val < *res {
// *res = root.Val - prev.Val
// // fmt.Printf("root = %v, prev = %v\n", root.Val, prev.Val)
// }
// }
fmt.Printf("root1 = %v, prev1 = %v\n", root.Val, prev.Val)
prev = root
dfs(root.Right, prev, res)
}
解决方法:
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func getMinimumDifference(root *TreeNode) int {
prev := &TreeNode{
Val : -1,
Left : nil,
Right : nil,
}
res := math.MaxInt64
dfs(root, prev, &res)
return res
}
func dfs(root *TreeNode, prev *TreeNode, res *int) {
if root == nil {
return
}
dfs(root.Left, prev, res)
if prev.Val != -1 {
if root.Val - prev.Val < *res {
*res = root.Val - prev.Val
}
}
// prev = root会产生问题!!!
prev.Val = root.Val
prev.Left = root.Left
prev.Right = root.Right
dfs(root.Right, prev, res)
}
2.2. 迭代
中序遍历模板题
3. 代码
3.1. 递归代码
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func getMinimumDifference(root *TreeNode) int {
var prev int = -1
res := math.MaxInt64
dfs(root, &prev, &res)
return res
}
func dfs(root *TreeNode, prev *int, res *int) {
if root == nil {
return
}
dfs(root.Left, prev, res)
if *prev != -1 {
if root.Val - *prev < *res {
*res = root.Val - *prev
}
}
// fmt.Printf("root = %v, prev = %v\n", root.Val, *prev )
*prev = root.Val
dfs(root.Right, prev, res)
}
3.2. 迭代代码(中序遍历模板题)
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func getMinimumDifference(root *TreeNode) int {
if root == nil {
return -1
}
var stack []*TreeNode
var pre *TreeNode
node := root
res := math.MaxInt64
for node!= nil || len(stack) > 0 {
for node != nil {
stack = append(stack, node)
node = node.Left
}
top := stack[len(stack) - 1]
if pre != nil {
if res > (top.Val - pre.Val) {
res = top.Val - pre.Val
}
}
pre = top
stack = stack[:len(stack) - 1]
node = top.Right
}
return res
}