zoukankan      html  css  js  c++  java
  • LeetCode-124. Binary Tree Maximum Path Sum

    Given a non-empty binary tree, find the maximum path sum.

    For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

    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

    递归

        int re ; 
        public int maxPathSum(TreeNode root) {
            re = Integer.MIN_VALUE;
            help(root);
            return re;
        }
        
        private int help(TreeNode root){
            if(root ==null){
                return 0;
            }
            int left = help(root.left);
            left = left>0?left:0;
            int right = help(root.right);
            right = right>0?right:0;
            int v = left+right+root.val;
            re = re>v?re:v;
            return left>right?(left+root.val):(right+root.val);
        }
  • 相关阅读:
    golang recover
    golang sort
    golang matrix
    golang encoding/json
    go package的理解
    golang beego cache
    git操作
    阿里云图标使用
    Stylus的使用
    vue-preview的使用
  • 原文地址:https://www.cnblogs.com/zhacai/p/11165710.html
Copyright © 2011-2022 走看看