【leetcode】Binary Tree Maximum Path Sum

原创 2015年07月07日 10:22:19

Problem

这里写图片描述

Hint

DFS

Code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int maxPath(struct TreeNode *root,int *rec){
    if(root==NULL)  return 0;
    int left = maxPath(root->left,rec);
    int right = maxPath(root->right,rec);
    if(left<0)  left = 0;
    if(right<0) right = 0;
    *rec = *rec>left+right+root->val?*rec:left+right+root->val;
    return (left>right?left:right)+root->val;
}
int maxPathSum(struct TreeNode* root) {
    int max = 0x80000000;
    maxPath(root,&max);
    return max;
}

The elegance of algorithm must be tasted by racking your brain. : )

版权声明:Pain is just in your mind.

相关文章推荐

【leetcode】binary-tree-maximum-path-sum

/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * ...
  • WX_East
  • WX_East
  • 2017年06月21日 15:32
  • 186

【LeetCode】Binary Tree Maximum Path Sum 解题报告

【题目】 Given a binary tree, find the maximum path sum. The path may start and end at any node ...
  • ljiabin
  • ljiabin
  • 2015年01月22日 16:15
  • 3066

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

LeetCode(124) 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 ...

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

Leetcode 124 Binary Tree Maximum Path Sum 二叉树最大路径和

给出一棵二叉树,计算其最大路径和。路径的起止结点必须位于树内。

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

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
  • 1725

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

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

1 解题思想在二叉树当中,找到一条路径,这条路径的和最大。这里所谓的路径,就是每个节点只经过一次的一条路径,可以选择在任何节点开始,也可以选择在任何节点结束本质上,其有点像用DP的递归方式搜索,因为每...
  • MebiuW
  • MebiuW
  • 2016年10月13日 19:13
  • 442
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:【leetcode】Binary Tree Maximum Path Sum
举报原因:
原因补充:

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