【Java|golang】1026. 节点与其祖先之间的最大差值---避坑,注意:golang中同一个包下的全局变量只加载一次。
给定二叉树的根节点 root,找出存在于 不同 节点 A 和 B 之间的最大值 V,其中 V = |A.val - B.val|,且 A 是 B 的祖先。
(如果 A 的任何子节点之一为 B,或者 A 的任何子节点是 B 的祖先,那么我们认为 A 是 B 的祖先)
示例 1:
输入:root = [8,3,10,1,6,null,14,null,null,4,7,13]
输出:7
解释:
我们有大量的节点与其祖先的差值,其中一些如下:
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
在所有可能的差值中,最大值 7 由 |8 - 1| = 7 得出。
示例 2:
输入:root = [1,null,2,null,0,3]
输出:3
提示:
树中的节点数在 2 到 5000 之间。
0 <= Node.val <= 105
int res=0;public int maxAncestorDiff(TreeNode root) {dfs(root,root.val,root.val);return res;}public void dfs(TreeNode root,int max,int min) {if (root==null){return;}if (root.val>max){max= root.val;}if (root.val<min){min= root.val;}res=Math.max(max-min,res);dfs(root.left,max,min);dfs(root.right,max,min);}
正确定义全局变量:
var res int
func maxAncestorDiff(root *TreeNode) int {res=0dfs(root,root.Val,root.Val)return res
}func dfs(root *TreeNode, max int, min int) {if root == nil {return}if root.Val > max {max = root.Val}if root.Val < min {min = root.Val}if max-min>res {res=max-min}dfs(root.Left, max, min)dfs(root.Right, max, min)
}
错误代码:
var res=0
func maxAncestorDiff(root *TreeNode) int {dfs(root,root.Val,root.Val)return res
}func dfs(root *TreeNode, max int, min int) {if root == nil {return}if root.Val > max {max = root.Val}if root.Val < min {min = root.Val}if max-min>res {res=max-min}dfs(root.Left, max, min)dfs(root.Right, max, min)
}