LeetCode_Binary Tree Maximum Path Sum

一.题目

Binary Tree Maximum Path Sum

   Total Accepted: 41576  Total Submissions: 193606 My Submissions

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

Discuss













二.解题技巧

    这道题仍然是二叉树的深度优先搜索,不过在进行遍历的时候需要考虑几个问题,最大路径和可能是以根结点的左右子树串联起来的路径,也可能是左子树或者右子树加上根结点,因此,在递归过程中要同时考虑这两个问题,这样就可以在递归过程中找到最大路径和。
    这道题的时间复杂度以及空间复杂度与普通的二叉树深度优先搜索相同,时间复杂度为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;
    }
};




四.体会

   这道题也是二叉树深度搜索的一个变种,主要难点在于考察最大的路径和可能出现在以整个子树中,也可能出现在左子树或者右子树上,不过也只有这两种情况需要考虑,并不需要考虑其他情况。



版权所有,欢迎转载,转载请注明出处,谢谢微笑





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值