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

问题:

难度:madium

说明:

熟悉的二叉树算法,算出有祖先子辈关系的两个树节点最大相减绝对值。

题目连接:https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/


我的代码:

也使用递归处理就好

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

猜你喜欢

转载自blog.csdn.net/qq_28033719/article/details/109581205