zoukankan      html  css  js  c++  java
  • Leetcode 124 二叉树的最大路径和

    题目描述:

     

    题解:二叉树的递归遍历求解。每个节点递归的结果为该节点的最大贡献,具体解释看代码。

    AC代码:

    class Solution {
    public:
        int del(TreeNode* root)
        {
            if(root == NULL) return 0;
            int tmp = root->val;
            int l = del(root->left);
            int r = del(root->right);
            ans = max(ans,max(tmp+max(l,r),tmp+l+r)); // 这里还多了一种左、右子树都取的情况,意在当前节点作为路径中的最高祖先
            ans = max(ans,tmp);
            return max(tmp,tmp+max(l,r));// 左、右子树取一个贡献较大的与当前节点的值相加 以及 只取当前节点两种情况
        }
    
        int maxPathSum(TreeNode* root) {
            ans = INT_MIN;
            del(root);
            return ans;
        }
    
    private:
        int ans;
    };
  • 相关阅读:
    Flesch Reading Ease (poj 3371)
    保留道路
    列车调度
    三角形
    高精度加法
    AC自动机(1)
    线段树
    并查集(3)
    并查集(2)
    并查集
  • 原文地址:https://www.cnblogs.com/z1141000271/p/12420305.html
Copyright © 2011-2022 走看看