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;
    }
};
发布了34 篇原创文章 · 获赞 0 · 访问量 572

猜你喜欢

转载自blog.csdn.net/Luyoom/article/details/104939985