博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【leetcode】Binary Tree Maximum Path Sum
阅读量:4705 次
发布时间:2019-06-10

本文共 1668 字,大约阅读时间需要 5 分钟。

Question :  

 

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:

Given the below binary tree,

1      / \     2   3

 

Return 6.

 

Anwser 1 :    

 

/**  * Definition for binary tree  * struct TreeNode {  *     int val;  *     TreeNode *left;  *     TreeNode *right;  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}  * };  */ class Solution { public:     int calLen(TreeNode *root, int &len)     {         if (root == NULL)         {             len = 0;             return 0;         }                  if (root->left == NULL && root->right == NULL)         {             len = root->val;             return root->val;         }                  int leftPath, rightPath;         int leftLen;         if (root->left)             leftLen = calLen(root->left, leftPath);         else         {             leftLen = INT_MIN;             leftPath = 0;         }                  int rightLen;         if (root->right)             rightLen = calLen(root->right, rightPath);         else         {             rightLen = INT_MIN;             rightPath = 0;         }                  len = max(max(leftPath, rightPath) + root->val, root->val);         int maxLen = max(root->val, max(leftPath + rightPath + root->val,              max(leftPath + root->val, rightPath + root->val)));                  return max(max(leftLen, rightLen), maxLen);     }          int maxPathSum(TreeNode *root) {         // Start typing your C/C++ solution below         // DO NOT write int main() function         int len;         return calLen(root, len);     } };

 

 

 

 

转载于:https://www.cnblogs.com/xinyuyuanm/archive/2013/05/01/3053872.html

你可能感兴趣的文章
(转)Excel的 OleDb 连接串的格式(连接Excel 2003-2013)
查看>>
Java并发编程
查看>>
Git Stash用法
查看>>
sql server 2008学习8 sql server存储和索引结构
查看>>
Jquery radio选中
查看>>
memcached 细究(三)
查看>>
RSA System.Security.Cryptography.CryptographicException
查看>>
webservice整合spring cxf
查看>>
[解题报告] 100 - The 3n + 1 problem
查看>>
Entity Framework 学习高级篇1—改善EF代码的方法(上)
查看>>
Mybatis逆向工程配置文件详细介绍(转)
查看>>
String类的深入学习与理解
查看>>
不把DB放进容器的理由
查看>>
OnePage收集
查看>>
Java parseInt()方法
查看>>
yahoo的30条优化规则
查看>>
[CCF2015.09]题解
查看>>
[NYIST15]括号匹配(二)(区间dp)
查看>>
json_value.cpp : fatal error C1083: 无法打开编译器生成的文件:No such file or directory
查看>>
洛谷 P1101 单词方阵
查看>>