码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ:Binary Tree Maximum Path Sum(二叉树最大路径和)

时间:2015-10-28 21:05:06      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

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.

求二叉树的最大路径和,感觉好复杂,但是分析一下,由于中间的点不能重叠,所以说肯定一部分在某个点的左边一个在右边。所以可以遍历左右子树来求最大值,相当于遍历所有的单点以及其左右子树之后,不断的更新最大值,用ret全局变量来维护这个最大值。将总体当作根节点加上左边和右边就可以了,代码如下:

 1 class Solution {
 2 public:
 3     int maxPathSum(TreeNode *root) {
 4         if(!root) return ret;
 5         ret = INT_MIN;
 6         dfs(root);
 7         return ret;
 8     }
 9 
10     int dfs(TreeNode * node)
11     {
12         if(node == NULL) return 0;
13         int val = node->val;
14         int left = dfs(node->left);
15         int right = dfs(node->right);
16         if(left > 0) val += left;
17         if(right > 0) val += right;
18         if(val > ret)
19             ret = val;
20         return max(node->val, max(node->val + left, node->val + right));
21     }
22 private:
23     int ret;
24 };

 

LeetCode OJ:Binary Tree Maximum Path Sum(二叉树最大路径和)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/4918464.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!