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

[LeetCode] Binary Tree Maximum Path Sum

时间:2015-01-18 13:00:09      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

       1
      /      2   3

 

Return 6.

思路:一下讲解来自于http://www.cnblogs.com/shawnhue/archive/2013/06/08/leetcode_124.html

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     bool is_valid_ = false;
13     int max_sum = INT_MIN;
14     int maxPathSum(TreeNode *root) {
15         if (root == NULL) return max_sum;
16         Dfs(root);
17         is_valid_ = true;
18         return max_sum;
19     }
20     
21     //后序递归
22     int Dfs(TreeNode *root) {
23         if (root == NULL) return 0;
24         int left_sum = Dfs(root->left);
25         int right_sum = Dfs(root->right);
26         int current_sum = root->val;
27         if (left_sum > 0) current_sum += left_sum;
28         if (right_sum > 0) current_sum += right_sum;
29         max_sum = max(max_sum, current_sum);
30         
31         return max(left_sum, right_sum) > 0 ? max(left_sum, right_sum) + root->val : root->val;
32     }
33 };

 

[LeetCode] Binary Tree Maximum Path Sum

标签:

原文地址:http://www.cnblogs.com/vincently/p/4231670.html

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