题目:

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;
}

 

相关文章:

  • 2021-09-17
  • 2021-11-12
  • 2021-09-15
  • 2021-07-04
  • 2021-05-20
  • 2021-06-27
猜你喜欢
  • 2022-01-14
  • 2021-07-10
  • 2021-08-05
  • 2021-10-09
  • 2021-06-08
相关资源
相似解决方案