leetcode 124. Binary Tree Maximum Path Sum 最大路径和 + DFS深度优先搜索

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 must contain at least one node and does not need to go through the root.

For example:
Given the below binary tree,

   1
  / \
 2   3

Return 6.

这道题求的是通过父子关系连接起来的最大的路径和,路径的起始结点不一定是叶子节点。

我看了这道题好久才明白,那么我们可以利用DFS深度优先搜索来得到左右结点的最大sum,然后更新最大的路径sum。

建议和leetcode 437. Path Sum III 深度优先遍历DFSleetcode 687. Longest Univalue Path 深度优先遍历DFS 一起学习

代码如下:


/*class TreeNode 
{
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
}*/


/*
 * 函数递归返回的是某一路径的最大sum
 * 那么对于某一个结点,更新相关详细即可
 * 如果只是一个节点,那么当然就是这个节点的值了.
 * 
 * */
public class Solution
{
    int MaxPathSum = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) 
    {
        maxPathSumByRecursion(root);
        return MaxPathSum;
    }

    public int maxPathSumByRecursion(TreeNode root) 
    {
        if(root==null)
            return 0;
        else
        {
            int leftMax = maxPathSumByRecursion(root.left);
            int rightMax = maxPathSumByRecursion(root.right);
            int tmp = root.val;
            if(leftMax>0)
                tmp += leftMax;
            if(rightMax>0)
                tmp += rightMax;
            //这里更新最大路径值
            MaxPathSum = Math.max(MaxPathSum, tmp);

            //这里返回的是当前左孩子或者右孩子的最大的sum,并不是某一条路径的最大sum
            return Math.max(root.val, Math.max(leftMax + root.val, rightMax + root.val));
        }
    }
}

下面手C++的做法,就是DFS深度优先遍历的做法,这里要注意两个问题:
我们是用DFS递归来计算某一个路径的sum,然后在递归计算中间计算比较最大的路径值

代码如下:

#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>

using namespace std;

/*
struct TreeNode 
{
     int val;
     TreeNode *left;
     TreeNode *right;
     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
*/

class Solution 
{
public:
    int maxSum = numeric_limits<int>::min();
    int maxPathSum(TreeNode* root) 
    {
        if (root == NULL)
            return 0;
        byDFS(root);
        return maxSum;
    }

    int byDFS(TreeNode* root)
    {
        if (root == NULL)
            return 0;
        else
        {
            int left = byDFS(root->left);
            int right = byDFS(root->right);
            int tmp = root->val;
            if (left > 0)
                tmp += left;
            if (right > 0)
                tmp += right;
            maxSum = max(maxSum, tmp);
            return max(root->val,max(left+root->val,right + root->val));
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值