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:

1026. Maximum Difference Between Node and Ancestor

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 }

 



上一篇:Leetcode练习(Python):滑动窗口:第239题:滑动窗口最大值:给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字


下一篇:[CF1082D]Maximum Diameter Graph