zoukankan      html  css  js  c++  java
  • [LeetCode]Binary Tree Maximum Path Sum

    Given a binary tree, find the maximum path sum.

    The path may start and end at any node in the tree.

    For example:
    Given the below binary tree,

           1
          / 
         2   3
    

     

    Return 6.

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    private:
        int ans;
    public:
        int DFS(TreeNode *root)
        {
            if(root==NULL) return 0;
            else
            {
                int sum=root->val;
                int sum1=DFS(root->left);
                int sum2=DFS(root->right);
                if(sum1>0) sum+=sum1;
                if(sum2>0) sum+=sum2;
                ans=max(ans,sum);
                return max(root->val,max(root->val+sum1,root->val+sum2));
            }
        }
        int maxPathSum(TreeNode *root) {
            if(root==NULL) return 0;
            ans=root->val;
            return max(ans,DFS(root));
        }
    };
    

      

  • 相关阅读:
    讨论一下,乌云漏洞库的学习方法
    a
    asss
    密码重置
    SQL注入2
    起名字真难
    Header
    SQL注入1
    伪装者
    ofbiz 代码日记
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3461183.html
Copyright © 2011-2022 走看看