递归+遍历二叉树 124. 二叉树中的最大路径和

36 篇文章 0 订阅
13 篇文章 0 订阅

124. 二叉树中的最大路径和

给定一个非空二叉树,返回其最大路径和。

本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。

示例 1:

输入: [1,2,3]

       1
      / \
     2   3

输出: 6

示例 2:

输入: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

输出: 42

解题:1
对每个节点得到左边的最大值和右边的最大值,然后求最大值;
复杂度N^2,效率过低;

/**
 * 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 maxPathSum(TreeNode* root) {
        res=root->val;
        //res=0;
        dfs(root);
        return res;
    }
private:
    int t;
    int res;
    int res1;
    int res2;
    void dfs1(TreeNode *root)
    {
        if(!root) return;
        t+=root->val;
        res1=max(res1,t);
        dfs1(root->left);
        dfs1(root->right);
        t-=root->val;
        return;
    }
    void dfs2(TreeNode *root)
    {
        if(!root) return;
        t+=root->val;
        res2=max(res2,t);
        dfs2(root->left);
        dfs2(root->right);
        t-=root->val;
        return;
    }
    void dfs(TreeNode * root){
        if(!root) return;
        res1=0;
        res2=0;
        t=0;
        dfs1(root->left);
        t=0;
        dfs2(root->right);
        res=max(res,root->val+res1+res2);
        dfs(root->left);
        dfs(root->right);
        return;
    } 
};

清晰的递归思路
递归函数:得到该点往下遍历的一条线上的最大值;
每次返回往左遍历和往右子树遍历的大者;

而结果res中取res与当前节点和左右节点的最大值保存;

注意点
左右节点的最小值为0,表示不取后面的节点!;

/**
 * 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 maxPathSum(TreeNode* root) {
        res=root->val;
        findmax(root);
        return res;
    }
private:    
    int res;
    int findmax(TreeNode * root){
        if(!root) return 0;
        int leftmax=max(0,findmax(root->left));
        int rightmax=max(0,findmax(root->right));
        res=max(res,root->val+leftmax+rightmax);   //少于0的不选
        return root->val+max(leftmax,rightmax);
    }
};

总结
递归表示得到一条线上的节点;
结果保存两条路线+根节点的和;
递归函数的结果可以作为答案的一个分支来解题,得到答案;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值