Binary Tree Maximum Path Sum

转载 2015年07月06日 18:55:26
/**
 * 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 res = INT_MIN;
        dfs(root,res);
        return res;
    }
    int dfs(TreeNode* root,int & res)
    {
        if (!root)
            return 0;
        int left = dfs(root->left,res);
        int right = dfs(root->right,res);
        int cur = root->val + (left > 0 ? left : 0) + (right > 0 ? right : 0);
        res = max(res,cur);
        return root->val + max(max(left,right),0);
    }
};
参考了 http://blog.csdn.net/linhuanmars/article/details/22969069

LeetCode: Binary Tree Maximum Path Sum [124]

【题目】 Given a binary tree, find the maximum path sum. The path may start and end at any node in the...

#94 Binary Tree Maximum Path Sum

题目描述: Given a binary tree, find the maximum path sum. The path may start and end at any node...

LeetCode(124) Binary Tree Maximum Path Sum

题目 Given a binary tree, find the maximum path sum. For this problem, a path is defined as any seq...
  • fly_yr
  • fly_yr
  • 2015年12月27日 16:20
  • 1781

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 tre...

124. Binary Tree Maximum Path Sum

Given a binary tree, find the maximum path sum. For this problem, a path is defined as any sequen...

Leetcode 124. Binary Tree Maximum Path Sum 最大路径和 解题报告

1 解题思想在二叉树当中,找到一条路径,这条路径的和最大。这里所谓的路径,就是每个节点只经过一次的一条路径,可以选择在任何节点开始,也可以选择在任何节点结束本质上,其有点像用DP的递归方式搜索,因为每...
  • MebiuW
  • MebiuW
  • 2016年10月13日 19:13
  • 483

LeetCode 124. Binary Tree Maximum Path Sum

1. 题目描述 Given a binary tree, find the maximum path sum. For this problem, a path is defined a...

[LeetCode 124] Binary Tree Maximum Path Sum (DFS/二叉树)

递归求解二叉树
  • zlasd
  • zlasd
  • 2016年09月21日 12:03
  • 208

124:Binary Tree Maximum Path Sum【树】【DFS】

题目链接:click~ /*题意:给定一颗二叉树,求最大路径和。路径可以从任意结点开始,任意结点结束*/ /** *思路: 对于每个结点,需要比较三个值 * 1)左子结点为结尾的路...

LEETCODE 124. Binary Tree Maximum Path Sum

题目大意给出一棵二叉树,求出里面的每个节点加起来值最大的路径的和。解题思路解决这一题的思路主要是遍历每一个点i,计算以这个点为根节点,并经过这个点的路径和的最大值,记作pathSum(i),这个值可...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Binary Tree Maximum Path Sum
举报原因:
原因补充:

(最多只允许输入30个字)