算法练习笔记(八)—— 寻找最大路径树

在一棵树之中寻找最大和的路径

在刚开始可能会使我们感到迷惑

但是在找到其中的原理,再运用递归

便能够巧妙地将其表示出来!

题目地址:https://leetcode.com/problems/binary-tree-maximum-path-sum/#/description

题目:Binary Tree Maximum Path Sum

描述:

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.

解答:

class Solution {
public:
    int maxToRoot(TreeNode*root, int& re){
        if (!root) return 0;
        int l = maxToRoot(root->left, re);
        int r = maxToRoot(root->right, re);
        if (l < 0) l = 0;
        if (r < 0) r = 0;
        if (l + r + root->val > re) re = l + r + root->val;
        return root->val += max(l, r);
    }
    int maxPathSum(TreeNode* root) {
        int max = -2147483648;
        maxToRoot(root, max);
        return max;
    }
};

参考了解法中O(n)的答案,简而言之,便是解析其中原理,总而言之,max刚开始设置为最小负数,防止树中存在着负值,并将地址传到函数之中,在函数遍历每个结点时,现将左子树和右子树中链接其根节点最大路径算出,re值代表着目前为止所遍历的结点中,最大路径的值,就这样层层推进,除去左子树+右子树+根这样特殊的情况,便能得出最大的路径值。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值