• (算法)Binary Tree Max Path Sum


    题目:

    Given a 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 does not need to go through the root.

    For example:
    Given the below binary tree,

           1
          / 
         2   3
    

    Return 6.

    思路:

    递归

    代码:

    #include<iostream>
    #include<stdlib.h>
    
    using namespace std;
    
    struct TreeNode{
        int val;
        TreeNode* left;
        TreeNode* right;
    };
    
    int maxPathSum(TreeNode *root,int &maxDist){
        if(root==NULL)
            return 0;
    
        int lmax=maxPathSum(root->left,maxDist);
        int rmax=maxPathSum(root->right,maxDist);
    
        if(lmax+rmax+root->val>maxDist)
            maxDist=lmax+rmax+root->val;
    
        return max(0,root->val+max(lmax,rmax));
    }
    
    int main(){
    
        return 0;
    }
  • 相关阅读:
    【贪心】时空定位I
    【贪心】删数问题
    【贪心】取火柴游戏
    【贪心】均分纸牌
    Fix a Tree
    Vacations
    One Bomb
    Abandoned country
    BZOJ 1006 [HNOI2008]神奇的国度
    BZOJ 2118 墨墨的等式
  • 原文地址:https://www.cnblogs.com/AndyJee/p/4896364.html
Copyright © 2020-2023  润新知