首页 > 其他 > 详细

1026. Maximum Difference Between Node and Ancestor

时间:2020-04-05 11:36:33      阅读:66      评论:0      收藏:0      [点我收藏+]

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 }

 



1026. Maximum Difference Between Node and Ancestor

原文:https://www.cnblogs.com/beiyeqingteng/p/12636198.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!