二叉树找路径上数值和的最大值(递归)

 

 

/**
 * 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 res = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        getMax(root);
        return res;
    }
    private int getMax(TreeNode r){
        if(r == null) return 0;
        int left = Math.max(0,getMax(r.left));
        int right = Math.max(0,getMax(r.right));
        res = Math.max(res,left + right + r.val);
        return Math.max(left,right)+r.val;
    }
}

 

posted @ 2021-08-31 15:38  K峰  Views(101)  Comments(0)    收藏  举报