From 44a58c488be33f1f43d60a6c9a30f243fe100527 Mon Sep 17 00:00:00 2001 From: ATRI2107 Date: Thu, 1 Oct 2020 11:47:21 +0530 Subject: [PATCH] Added a new Program with the best Execution Time --- ... Difference Between Node and Ancestor.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Medium/Maximum Difference Between Node and Ancestor.java diff --git a/Medium/Maximum Difference Between Node and Ancestor.java b/Medium/Maximum Difference Between Node and Ancestor.java new file mode 100644 index 00000000..19a9dda7 --- /dev/null +++ b/Medium/Maximum Difference Between Node and Ancestor.java @@ -0,0 +1,43 @@ +/** + * 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 res=Integer.MIN_VALUE; + int max(TreeNode root) + { + if(root==null) return Integer.MIN_VALUE; + if(root.left==null && root.right==null) return root.val; + int l=max(root.left); + int r=max(root.right); + int m=Math.max(l,r); + res=Math.max(res,Math.abs(root.val-m)); + return Math.max(root.val,m); + } + int min(TreeNode root) + { + if(root==null) return Integer.MAX_VALUE; + if(root.left==null && root.right==null) return root.val; + int l=min(root.left); + int r=min(root.right); + int m=Math.min(l,r); + res=Math.max(res,Math.abs(root.val-m)); + return Math.min(root.val,m); + } + public int maxAncestorDiff(TreeNode root) { + max(root); + min(root); + return res; + } +} \ No newline at end of file