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

Binary Tree Maximum Path Sum - LeetCode

时间:2016-05-08 06:44:03      阅读:146      评论: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.

思路:所求的maximum path sum有可能会包括一个根节点和两条分别在左右子树中的路径,这里构建一个新的树,每个节点存储的值为所给二叉树对应位置节点向下的最大单条路径(不会在根节点分叉)。然后遍历整个树,找到maximum path sum。

代码中copyTree函数为构建树。遍历树并找到maximum path sum在help函数中实现。

 1 class Solution {
 2 public:
 3     TreeNode* copyTree(TreeNode* root)
 4     {
 5         if (!root) return NULL;
 6         TreeNode* cur = new TreeNode(root->val);
 7         cur->left = copyTree(root->left);
 8         cur->right = copyTree(root->right);
 9         int largest = 0;
10         if (cur->left) largest = max(largest, cur->left->val);
11         if (cur->right) largest = max(largest, cur->right->val);
12         cur->val += largest;
13         return cur;
14     }
15     void help(TreeNode* root, TreeNode* cproot, int& res)
16     {
17         if (!root) return;
18         int localSum = root->val;
19         if (cproot->left && cproot->left->val > 0)
20             localSum += cproot->left->val;
21         if (cproot->right && cproot->right->val > 0)
22             localSum += cproot->right->val;
23         if (localSum > res) res = localSum;
24         help(root->left, cproot->left, res);
25         help(root->right, cproot->right, res);
26     }
27     int maxPathSum(TreeNode* root) {
28         TreeNode* cproot = copyTree(root);
29         int res = INT_MIN;
30         help(root, cproot, res);
31         return res;
32     }
33 };

 

Binary Tree Maximum Path Sum - LeetCode

标签:

原文地址:http://www.cnblogs.com/fenshen371/p/5469693.html

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