Wednesday, October 28, 2020

LeetCode [1026] Maximum Difference Between Node and Ancestor

 1026. Maximum Difference Between Node and Ancestor

Medium

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.

 

Note:

  1. The number of nodes in the tree is between 2 and 5000.
  2. Each node will have value between 0 and 100000.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
 * 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 {
    int dm = 0;
    public int maxAncestorDiff(TreeNode root) {
        if(root==null) return dm;
        helper(root, root.val, root.val);
        return dm;
    }
    
    void helper(TreeNode root, int aMax, int aMin){
        if(root==null) return;
        int d = Math.max(Math.abs(root.val-aMax), Math.abs(root.val-aMin));
        dm = Math.max(dm, d);
        aMax = Math.max(aMax, root.val);
        aMin = Math.min(aMin, root.val);
        helper(root.left, aMax, aMin);
        helper(root.right, aMax, aMin);
    }
}

No comments:

Post a Comment