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

二叉树?最大路径和!

题目:
给定一个非空二叉树,返回其最大路径和。
本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。

例子
示例 1:
输入: [1,2,3]

   1
  / \
 2   3

输出: 6

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

   -10
   / \
  9  20
    /  \
   15   7

输出: 42

题目分析
  • 目标:在二叉树中找一条路径 ⇒ 其节点和最大

对于某一结点
向前走 ⇒ 左结点 / 右结点
路径和 = 当前结点值 + 剩余路径(以左节点/右节点为起点)的结点值和 ⇒ 递归

解题思路
变量作用
find()寻找路径和

过程

  1. 把二叉树根结点放入队列 s
  2. 对于某一节点 ⇒ 寻找向左走(以左节点为起点)的路径和+向右走(以右节点为起点)的路径和
  3. 判断是否更新路径最大值
  4. 将左右结点加入队列 s 重复2,3

代码如下

int find(TreeNode*root)                                      //寻找 root 为起点的最大路径结点和
{
    if(!root) return 0;
    int left = 0, right = 0;
    if(!root->left && !root->right) return root->val;
    if(root -> left) left += find(root->left);
    if(root -> right) right += find(root->right);
    return max(max(root->val,root->val+left),root->val+right); 
}

class Solution {
public:
    int maxPathSum(TreeNode* root) {
        if(!root) return 0;
        int max0 = root->val;
        queue<TreeNode*> s{{root}};
        while(!s.empty())
        {
            TreeNode* temp = s.front();
            s.pop();
            int left = find(temp->left);        //向左走
            int right = find(temp->right);      //向右走
            max0 = max(max(max(temp->val,temp->val+left),max(temp->val+right,temp->val+left+right)),max0);        //判断是否更新最大值
            if(temp->left) s.push(temp->left);
            if(temp->right) s.push(temp->right);
        }
        return max0;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值