博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Binary Tree Maximum Path Sum
阅读量:6881 次
发布时间:2019-06-27

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

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.

1 /** 2  * Definition for binary tree 3  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 class Solution {11 public:12     int calLen(TreeNode *root, int &len)13     {14         if (root == NULL)15         {16             len = 0;17             return 0;18         }19         20         if (root->left == NULL && root->right == NULL)21         {22             len = root->val;23             return root->val;24         }25         26         int leftPath, rightPath;27         int leftLen;28         if (root->left)29             leftLen = calLen(root->left, leftPath);30         else31         {32             leftLen = INT_MIN;33             leftPath = 0;34         }35         36         int rightLen;37         if (root->right)38             rightLen = calLen(root->right, rightPath);39         else40         {41             rightLen = INT_MIN;42             rightPath = 0;43         }44         45         len = max(max(leftPath, rightPath) + root->val, root->val);46         int maxLen = max(root->val, max(leftPath + rightPath + root->val, 47             max(leftPath + root->val, rightPath + root->val)));48         49         return max(max(leftLen, rightLen), maxLen);50     }51     52     int maxPathSum(TreeNode *root) {53         // Start typing your C/C++ solution below54         // DO NOT write int main() function55         int len;56         return calLen(root, len);57     }58 };

转载地址:http://brubl.baihongyu.com/

你可能感兴趣的文章
Java使用jxl读取excel
查看>>
Grunt 插件开发与调式
查看>>
Python yield用法
查看>>
生成excel表报的控件FlexCel Studio for .NET
查看>>
使用SCVMM 2012 R2管理Hyper-v群集
查看>>
【开源社群系统研发日记五】ThinkSNS+ 是如何计算字符显示长度的
查看>>
Nodejs日志管理log4js
查看>>
php全文搜索引擎xunsearch的搭建
查看>>
HTTP 常见错误代码与含义
查看>>
我的友情链接
查看>>
不常用的console命令(一)
查看>>
control reaches end of non-void block
查看>>
MySQL Study之--MySQL schema_information数据库
查看>>
Hexo在github上搭载个人博客
查看>>
手机秒变IoT设备?——巧妙利用阿里云物联网平台
查看>>
跟黄哥学python序列文章之python 函数是第一类对象
查看>>
vue组件系列1、弹窗
查看>>
2013最多“情人节”婚庆网购窝窝商城掀热潮
查看>>
【转】linux下搭建生成HLS所需的.ts和.m3u8文件
查看>>
开通51cto博客
查看>>