• [LeetCode] Binary Tree Maximum Path Sum


    Given a non-empty 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.

    Example 1:

    Input: [1,2,3]
    
           1
          / 
         2   3
    
    Output: 6
    

    Example 2:

    Input: [-10,9,20,null,null,15,7]
    
       -10
       / 
      9  20
        /  
       15   7
    
    Output: 42

    首先一首凉凉送给自己,阿里面试官问了这道题。让我下来好好想一想。。

    首先,把每个节点当成根节点,计算通过这个点左右子树的最大路径。

    然后,试想,如果要求其左子树最大路径,那么就需要求出其左子树的两个子树中较大路径。右子树同理。

    最后,如果遇到负数,直接将其变成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) {
            if (root == NULL)
                return 0;
            // 维护最大值
            int res = INT_MIN;
            // 递归函数,目的在于求解以每个节点为根的最大路径之和(单边)
            helper(root, res);
            return res;
        }
        int helper(TreeNode* root, int& res)
        {
            if (root == NULL)
                return 0;
            // 左子树最大路径
            int l = max(helper(root->left, res), 0);
            // 右子树最大路径
            int r = max(helper(root->right, res), 0);
            // 维护最大结果
            res = max(res, l+r+root->val);
            return max(l, r)+root->val;
        }
    };
  • 相关阅读:
    Linux基础知识--目录操作
    Linux基础知识--命令的基础知识
    Linux基础知识--磁盘分区和目录结构
    PO设计模式
    SSL连接形式发送邮件
    已附件的形式发送测试报告
    Python+selenium+HTMLTestRunner邮件形式发送测试报告
    Python随笔13
    Python随笔12
    Python随笔11
  • 原文地址:https://www.cnblogs.com/immjc/p/9513897.html
Copyright © 2020-2023  润新知