首页 > 编程语言 > 详细

(算法)Binary Tree Max Path Sum

时间:2015-10-21 00:03:21      阅读:234      评论:0      收藏:0      [点我收藏+]

题目:

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

 

(算法)Binary Tree Max Path Sum

原文:http://www.cnblogs.com/AndyJee/p/4896364.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!