Leetcode:. 124 and the maximum path in the binary tree

Title:
Given a non-empty binary tree, and returns its maximum path.
In this problem, it is defined as a path from any node in the tree, to the sequence of any node. The path includes at least one node, and not necessarily through the root node.
Example 1:
Input: [1,2,3]

   1
  / \
 2   3

Output: 6
Example 2:
Input: [-10,9,20, null, null, 15,7]

-10
/
9 20
/
15 7

Output: 42

Learn codes from leetcode Comments

Appreciated:
1. The binary tree from a parent node to another node over the path of the two nodes will;
2. a sub-path from the node to the child node of the parent node of the parent node when ... except the last parent node other 'parent' nodes only through a sub-tree;

/**
 * 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 Review

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); //向上传递,每个节点选择左或者右边
           
    }

Guess you like

Origin blog.csdn.net/Fishandbearspaw/article/details/89006575