码迷,mamicode.com
首页 > 其他好文 > 详细

1026. Maximum Difference Between Node and Ancestor

时间:2020-04-05 12:01:52      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:inpu   tput   tco   solution   find   mpm   nan   any   return   

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

标签:inpu   tput   tco   solution   find   mpm   nan   any   return   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!