zoukankan      html  css  js  c++  java
  • 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

    解题思路:

    找到书中相邻节点最大的和。

    首先我们先观察那种可以组成和:

    1. 左节点->根节点<-右节点

    2.左节点->根节点

    3.根节点<-右节点

    4.根节点

    注意的是:

    若我们根节点连接左子树中的最大的和,即通过左孩子连到根节点,那么代表左子树中不能将左右节点通过根节点连起来。

    所以我们在遍历树时,返回以该节点为根的子树返回的不连接左右子节点的最大值。

    但是也可能我们要求的最大值存在与该节点连接其左右子树。

    所以我们要进行比较

    又做一遍之后发现之前的代码不够简洁,现在更新一下~

    代码:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int maxPathSum(TreeNode* root) {
            int maxV = INT_MIN;
            pathValue(root, maxV);
            return maxV;
        }
    private:
        int pathValue(TreeNode* root, int &maxV){
            //we calculate the largest Value which pass root
            if(!root) return 0;
            
            int leftV = pathValue(root->left, maxV);
            int rightV = pathValue(root->right, maxV);
            //calculate the subMax
            int subMax = max(root->val, leftV + root->val);
            subMax = max(subMax, rightV + root->val);
            
            maxV = max(subMax, maxV);
            maxV = max(maxV, leftV + root->val + rightV);
            
            return subMax;
        }
    };
  • 相关阅读:
    axublogcms1.1.0 Getshell
    易酷 cms2.5 本地文件包含漏洞 getshell
    通过 phpmyadmin getshell
    python 简单图像识别--验证码
    Linux 入侵检测小结
    beef + msf 实现内网渗透
    phpwind v9存在命令执行漏洞(登陆后台)
    缓冲区溢出实践
    《Metasploit魔鬼训练营》第四章(下)
    《Metasploit魔鬼训练营》第四章(上)
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9219540.html
Copyright © 2011-2022 走看看