Leetcode:124. 二叉树中的最大路径和

题目:
给定一个非空二叉树,返回其最大路径和。
本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。
示例 1:
输入: [1,2,3]

   1
  / \
 2   3

输出: 6
示例 2:
输入: [-10,9,20,null,null,15,7]

-10
/
9 20
/
15 7

输出: 42

学习,代码来自leetcode评论

理解:
1.二叉树中的从一个节点到另一个节点的路径必过两节点的父节点;
2.路径是从一个子节点到该子节点的父节点的父节点…时,除了最后一个父节点,其他‘父’节点只能经过一个子树;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int max = Integer.MIN_VALUE;
    
    public int maxPathSum(TreeNode root) {
        backtrack(root);
        return max;
    }
    private int backtrack(TreeNode root){
        if(root == null) return Integer.MIN_VALUE;
        int left = backtrack(root.left);
        int right = backtrack(root.right);
       //代码优化:这是多余的,因为判断root节点下的左右子树是否为最大的,在上面int left,right语句的pick root 中就已经判断了
       // 多余。max = Math.max(max,Math.max(right,left));       //pick left branch or right branch
        max = Math.max(max,root.val);                   //pick root
        max = Math.max(max,root.val+Math.max(0,left)+ Math.max(0,right)  ); // pick root + MAX(0,left) + MAX(0,right)
        return root.val + Math.max(0,Math.max(left,right));
    }
}

4.10回顾

class Solution {
    int max=Integer.MIN_VALUE;// MIN_VALUE部分全要大写
    
    public int maxPathSum(TreeNode root) {
        dg(root);
        
        return max;
    }
    
    public int dg (TreeNode root){
        if(root==null)return 0;

        int left=dg(root.left);
        int right=dg(root.right);
        
        //if(root.left!=null)left=root.left.val;//错误:这样只能得到左边右边的各一个,我们需要的是长条
        //if(root.right!=null)right=root.right.val;//
        
        max=Math.max(root.val,max);//自身;
        
        max=Math.max(root.val+Math.max(left,0),max);//Math.max(left,0)不这样写,而是直接写+left可能会溢出; //本身加左边
        max=Math.max(root.val+Math.max(right,0),max); //本身加右边
        
        max=Math.max(root.val+Math.max(left,0)+Math.max(right,0),max); //本身加两边;
            
            
        return root.val+Math.max(Math.max(left,right),0); //向上传递,每个节点选择左或者右边
           
    }

猜你喜欢

转载自blog.csdn.net/Fishandbearspaw/article/details/89006575