1026. Maximum Difference Between Node and Ancestor

Given the root of a binary tree, find the maximum value V for which there exists different nodes A and B where V = |A.val - B.val| and A is an ancestor of B.

(A node A is an ancestor of B if either: any child of A is equal to B, or any child of A is an ancestor of B.)

 

Example 1:

Input: [8,3,10,1,6,null,14,null,null,4,7,13]
Output: 7
Explanation: 
We have various ancestor-node differences, some of which are given below :
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.

因为是比较最大 difference, 可以是正数,也可以是负数。
 1 class Solution {
 2     public int maxAncestorDiff(TreeNode root) {
 3         int[] tempMax = { 0 };
 4         helper(root, root.val, root.val, tempMax);
 5         return tempMax[0];
 6     }
 7     
 8     public void helper(TreeNode root, int maxAncestor, int minAncestor, int[] tempMax) {
 9         if (root == null) return;
10         tempMax[0] = Math.max(tempMax[0], Math.abs(maxAncestor - root.val));
11         tempMax[0] = Math.max(tempMax[0], Math.abs(minAncestor - root.val));
12         maxAncestor = Math.max(maxAncestor, root.val);
13         minAncestor = Math.min(minAncestor, root.val);
14         
15         helper(root.left, maxAncestor, minAncestor, tempMax);
16         helper(root.right, maxAncestor, minAncestor, tempMax);
17     }
18 }

 



posted @ 2020-04-05 10:46  北叶青藤  阅读(263)  评论(0编辑  收藏  举报