问题:
给定二叉树的根节点 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
思路:
根据二叉树前序遍历的思想对二叉树进行嵌套递归,不仅对每个树节点进行前序遍历还对每个节点的孩子节点进行前序遍历。
代码:
/**
* 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) {
int ans = 0;
ans = preMethod(ans,root);
return ans;
}
public int preMethod(int ans, TreeNode root){
if(root == null){
return ans;
}
int lans = preChlidMethod(ans,root,root.left);
int rans = preChlidMethod(ans,root,root.right);
int tem = Math.max(lans,rans);
ans = Math.max(ans,tem);
int llans = preMethod(ans,root.left);
int rrans = preMethod(ans,root.right);
int ttem = Math.max(llans,rrans);
ans = Math.max(ttem,ans);
return ans;
}
public int preChlidMethod(int ans, TreeNode root, TreeNode child){
if(root !=null && child != null){
ans = Math.max(Math.abs(root.val - child.val),ans);
int ansl = preChlidMethod(ans,root,child.left);
int ansr = preChlidMethod(ans,root,child.right);
int tem = Math.max(ansl,ansr);
ans = Math.max(tem,ans);
return ans;
}
else {
return ans;
}
}
}