一.题目
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
.
Show Tags
Have you met this question in a real interview?
Yes
No
二.解题技巧
这道题仍然是二叉树的深度优先搜索,不过在进行遍历的时候需要考虑几个问题,最大路径和可能是以根结点的左右子树串联起来的路径,也可能是左子树或者右子树加上根结点,因此,在递归过程中要同时考虑这两个问题,这样就可以在递归过程中找到最大路径和。
这道题的时间复杂度以及空间复杂度与普通的二叉树深度优先搜索相同,时间复杂度为O(n),空间复杂度为O(logn)。
三.实现代码
#include <iostream>
#include <vector>
#include <climits>
using std::vector;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
private:
int maxPathSum(TreeNode *root, int &Result)
{
if (!root)
{
return 0;
}
int RootResult = root->val;
int LeftResult = maxPathSum(root->left, Result);
int RightResult = maxPathSum(root->right, Result);
LeftResult = LeftResult * (LeftResult > 0);
RightResult = RightResult * (RightResult > 0);
// all the tree
int TmpResult = RootResult + LeftResult + RightResult;
if (Result < TmpResult)
{
Result = TmpResult;
}
// only left subtree or the right subtree
TmpResult = RootResult + (LeftResult > RightResult? LeftResult : RightResult);
if (Result < TmpResult)
{
Result = TmpResult;
}
return TmpResult;
}
public:
int maxPathSum(TreeNode* root)
{
int Result = INT_MIN;
maxPathSum(root, Result);
return Result;
}
};
四.体会
这道题也是二叉树深度搜索的一个变种,主要难点在于考察最大的路径和可能出现在以整个子树中,也可能出现在左子树或者右子树上,不过也只有这两种情况需要考虑,并不需要考虑其他情况。
版权所有,欢迎转载,转载请注明出处,谢谢
