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
.
基本思路:
路径为,左子树的深度+根结点值+右子树的深度。
对每一个结点,都作如上运算,并把路径最大值存在一个全局变量中。
另外,此题,由于结点值存在负数。当树深度为负时,需要舍弃。因为对最长路径没有帮助。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int maxPathSum(TreeNode* root) { int max_path = INT_MIN; dfs(root, max_path); return max_path; } int dfs(TreeNode *root, int &max_path) { if (!root) return 0; int left = dfs(root->left, max_path); int right = dfs(root->right, max_path); max_path = max(max_path, left+right+root->val); return max(0, max(left, right)+root->val); } };
Binary Tree Maximum Path Sum -- leetcode
原文地址:http://blog.csdn.net/elton_xiao/article/details/45790657