Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * 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 {
- private int max = 0;
- public int maxAncestorDiff(TreeNode root) {
- max = 0;
- maxDiffFinderMax(root);
- maxDiffFinderMin(root);
- return max;
- }
- public int maxDiffFinderMax(TreeNode root) {
- if (root != null) {
- int left = root.left == null ? root.val : maxDiffFinderMax(root.left);
- int right = root.right == null ? root.val : maxDiffFinderMax(root.right);
- max = Math.max(max, Math.abs(root.val - left));
- max = Math.max(max, Math.abs(root.val - right));
- return Math.max(root.val, Math.max(left, right));
- }
- return 0;
- }
- public int maxDiffFinderMin(TreeNode root) {
- if (root != null) {
- int left = root.left == null ? root.val : maxDiffFinderMin(root.left);
- int right = root.right == null ? root.val : maxDiffFinderMin(root.right);
- max = Math.max(max, Math.abs(root.val - left));
- max = Math.max(max, Math.abs(root.val - right));
- return Math.min(root.val, Math.min(left, right));
- }
- return 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement