zoukankan      html  css  js  c++  java
  • leetcode@ [124] Binary Tree Maximum Path Sum (DFS)

    https://leetcode.com/problems/binary-tree-maximum-path-sum/

    Given a 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 does not need to go through the root.

    For example:
    Given the below binary tree,

           1
          / 
         2   3
    

    Return 6.

    /**
     * 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 res = INT_MIN;
        
        int dfs(TreeNode* root) {
            if(!root) return 0;
            
            int l = dfs(root->left);
            int r = dfs(root->right);
            
            int rhs = root->val;
            if(l > 0) rhs += l;
            if(r > 0) rhs += r;
            res = max(res, rhs);
            
            return max(l, r) <= 0? root->val: max(l, r) + root->val; 
        }
        
        int maxPathSum(TreeNode* root) {
            if(!root) return 0;
            
            dfs(root);
            
            return res;
        }
    };
    View Code
  • 相关阅读:
    20165312 我期望的师生关系
    zookeeper04---ZAB协议
    zookeeper03-集群搭建
    zookeeper02
    Zookeeper01
    防止重复提交
    手动抛出异常事务回滚问题
    redis-07主从复制
    redis06-事务
    Redis-05持久化
  • 原文地址:https://www.cnblogs.com/fu11211129/p/5098419.html
Copyright © 2011-2022 走看看