• leetcode124二叉树最大路径和


    第一选择是将其转化成图用动态规划,但这样还是太麻烦

    使用递归的思路,对于当前的节点root,分别求左右孩子到当前节点的单项路径权值最大的路径权值,然后记包含当前节点的路径权值为 path_price=root->val+left_gain+right_gain,取sum_max和他较大的;

    返回左右孩子权值最大的单向路径(只往上不拐弯)的权值(这需要好好理解,因为更新权值的式子是root->val+left_gain+right_gain,即从左子路到根再到右子路的一条式子,所以计算left_gain与right_gain需要返回这样的值)

    /**
     * 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) {
            //化为带权的图,求最大路径
            //递归,分解问题
            max_gain(root);
            return sum_max;
        }
        int max_gain(TreeNode* root){
            if(root==NULL) return 0;
            
            //0代表不选择该路径
            int left_gain=max(max_gain(root->left),0);
            int right_gain=max(max_gain(root->right),0);
            
            int path_price=root->val+left_gain+right_gain;
            sum_max=max(path_price,sum_max);
            
            //返回值//左右选一条是因为递归时,需要从子节点选一条路径到当前根节点;而当前最大值由sum_max记录
            return root->val+max(left_gain,right_gain);
        }
    private:
        int sum_max=INT_MIN;
    };

  • 相关阅读:
    error:Unterminated <form:form tag
    error:org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
    mvc-dispatchar-servlet.xml文件报错
    修改MySQL密码
    Injection of autowired dependencies failed
    IDEA jsp模板
    jstl的表达式不能解析
    前端学习的小窍门
    Git的使用
    MySql数据库表的查询操作
  • 原文地址:https://www.cnblogs.com/joelwang/p/11077337.html
Copyright © 2020-2023  润新知