1、节点与其祖先之间的最大差值(难度中等)
给定二叉树的根节点 root,找出存在于 不同 节点 A 和 B 之间的最大值 V,其中 V = |A.val - B.val|,且 A 是 B 的祖先。(如果 A 的任何子节点之一为 B,或者 A 的任何子节点是 B 的祖先,那么我们认为 A 是 B 的祖先)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int maxAncestorDiff(TreeNode root) {
return dfs(root, root.val, root.val);
}
public int dfs(TreeNode root, int mi, int ma) {
if (root == null) {
return 0;
}
int diff = Math.max(Math.abs(root.val - mi), Math.abs(root.val - ma));
mi = Math.min(mi, root.val);
ma = Math.max(ma, root.val);
diff = Math.max(diff, dfs(root.left, mi, ma));
diff = Math.max(diff, dfs(root.right, mi, ma));
return diff;
}
}
标签:TreeNode,val,int,mi,差值,二叉树,root,节点,Math
From: https://www.cnblogs.com/always0708/p/17329454.html