From b7e48c858301522a86fd2805d92c71971811205b Mon Sep 17 00:00:00 2001 From: ATRI2107 Date: Thu, 1 Oct 2020 12:07:19 +0530 Subject: [PATCH] Added a new Binary Tree Program --- ...mDifferenceBetweenNodeandAncestor1026.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/MaximumDifferenceBetweenNodeandAncestor1026.java diff --git a/src/MaximumDifferenceBetweenNodeandAncestor1026.java b/src/MaximumDifferenceBetweenNodeandAncestor1026.java new file mode 100644 index 0000000..19a9dda --- /dev/null +++ b/src/MaximumDifferenceBetweenNodeandAncestor1026.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