leetcode 124. Binary Tree Maximum Path Sum(Hard)

Problem :
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 does not need to go through the root.

Example:
Given the below binary tree,

   1
  / \
 2   3

Return 6.

Algorithm:
本题的意思为在一棵二叉树中寻找一条结点和最大的路径(不需要经过根节点)。这道题可采用递归的做法。
算法思路为,对于每一个给定结点,递归得到其左子树的最大值和右子树的最大值(注意,如果最大值的和小于0,则取最大值为0,表示不加入该条路径),再将其值与其左右子树的最大值相加,即可得到经过该结点的最大路径和。遍历完所有的结点,不断更新当前最大路径和,便可得到整棵树的最大路径和。由于每个结点只访问一次,因此该算法的时间复杂度为O(n)。

Code:

/**
 * 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 dfs(TreeNode* root) {
        if(!root) return 0;

        int lmax = dfs(root -> left);
        int rmax = dfs(root -> right);

        if(lmax < 0) lmax = 0;
        if(rmax < 0) rmax = 0;

        if(maxn < lmax + rmax + root -> val)
            maxn = lmax + rmax + root -> val;

        return max(lmax, rmax) + root -> val;
    }
    int maxPathSum(TreeNode* root) {
        if(!root) return 0;
        maxn = root -> val;

        dfs(root);

        return maxn;
    }
    int maxn;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值