LeetCode OJ: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.

求二叉树的最大路径和,感觉好复杂,但是分析一下,由于中间的点不能重叠,所以说肯定一部分在某个点的左边一个在右边。所以可以遍历左右子树来求最大值,相当于遍历所有的单点以及其左右子树之后,不断的更新最大值,用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 };

 

posted @ 2015-10-28 19:56  eversliver  阅读(299)  评论(0编辑  收藏  举报