Advertisement
rajeshinternshala

Untitled

Jan 11th, 2024
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.45 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * public class TreeNode {
  4.  * int val;
  5.  * TreeNode left;
  6.  * TreeNode right;
  7.  * TreeNode() {}
  8.  * TreeNode(int val) { this.val = val; }
  9.  * TreeNode(int val, TreeNode left, TreeNode right) {
  10.  * this.val = val;
  11.  * this.left = left;
  12.  * this.right = right;
  13.  * }
  14.  * }
  15.  */
  16. class Solution {
  17.     private int max = 0;
  18.  
  19.     public int maxAncestorDiff(TreeNode root) {
  20.         max = 0;
  21.         maxDiffFinderMax(root);
  22.         maxDiffFinderMin(root);
  23.         return max;
  24.  
  25.     }
  26.  
  27.     public int maxDiffFinderMax(TreeNode root) {
  28.         if (root != null) {
  29.             int left = root.left == null ? root.val : maxDiffFinderMax(root.left);
  30.             int right = root.right == null ? root.val : maxDiffFinderMax(root.right);
  31.             max = Math.max(max, Math.abs(root.val - left));
  32.             max = Math.max(max, Math.abs(root.val - right));
  33.             return Math.max(root.val, Math.max(left, right));
  34.  
  35.         }
  36.         return 0;
  37.     }
  38.  
  39.     public int maxDiffFinderMin(TreeNode root) {
  40.         if (root != null) {
  41.             int left = root.left == null ? root.val : maxDiffFinderMin(root.left);
  42.             int right = root.right == null ? root.val : maxDiffFinderMin(root.right);
  43.             max = Math.max(max, Math.abs(root.val - left));
  44.             max = Math.max(max, Math.abs(root.val - right));
  45.             return Math.min(root.val, Math.min(left, right));
  46.  
  47.         }
  48.         return 0;
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement