[Leetcode学习-java]Maximum Difference Between Node and Ancestor

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;
    }
}

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_28033719/article/details/109581205