leetcode(1026)节点与其祖先之间的最大差值

节点与其祖先之间的最大差值

class Solution {
        public int maxAncestorDiff(TreeNode root) {
        int leftmax = maxAncestorDiff2(root.left,root.val,root.val);
        int rightmax = maxAncestorDiff2(root.right,root.val,root.val);
        return Math.max(leftmax, rightmax);
    }
    public int maxAncestorDiff2(TreeNode root,int min,int max) {
        if(root==null) {
            return max-min;
        }
        if(root.val>max) {
            max = root.val;
        }
        if(root.val<min) {
            min = root.val;
        }
        int leftmax = maxAncestorDiff2(root.left,min,max);
        int rightmax = maxAncestorDiff2(root.right,min,max);
        return Math.max(leftmax, rightmax);
    }
}

 

posted @ 2019-07-05 17:27  海平面下的我们  阅读(243)  评论(0编辑  收藏  举报