problem:
Difficulty: major
Description:
The familiar binary tree algorithm calculates the absolute value of the maximum subtraction of two tree nodes that have an ancestor-child relationship.
Title link: https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/
My code:
Just use recursive processing
class Solution {
private static TreeNode max = new TreeNode(-1);
private static TreeNode min = new TreeNode(Integer.MAX_VALUE);
public int maxAncestorDiff(TreeNode root) {
return recurtion(max, min, root, 0);
}
public int recurtion(TreeNode max, TreeNode min, TreeNode root, int maxVal) {
if(root != null) {
if(root.val > max.val) max = root;
if(root.val < min.val) min = root;
maxVal = Math.max(Math.abs(max.val - min.val),
Math.max(recurtion(max, min, root.left, maxVal), recurtion(max, min, root.right, maxVal)));
}
return maxVal;
}
}