Binary Tree Maximum Path Sum (LeetCode)
来源:互联网 发布:push 数组 编辑:程序博客网 时间:2024/06/06 17:35
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
.
有一个地方要注意,如果left>0 && right>0,这时候的return value不能为(left+right+root.val),因为这样一来就不是一条single path了,必须取max(left,right)+root.val来返回
int max = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. return Math.max(maxHelper(root),max); } public int maxHelper(TreeNode root){ if(root==null) return 0; int sum=0, returnVal =0; int left = maxHelper(root.left); int right = maxHelper(root.right); if(left>0 && right>0){ sum = left+right+root.val; returnVal = Math.max(left,right)+root.val; } else if(left<0 && right<0){ sum = root.val; returnVal=root.val; } else{ sum = Math.max(left,right)+root.val; returnVal = Math.max(left,right)+root.val; } max = Math.max(max,sum); return returnVal; }
0 0
- *****(leetcode) Binary Tree Maximum Path Sum (tree)
- LeetCode Binary Tree Maximum Path Sum
- [Leetcode] Binary Tree Maximum Path Sum
- [leetcode] Binary Tree Maximum Path Sum
- LeetCode Binary Tree Maximum Path Sum
- [LeetCode] Binary Tree Maximum Path Sum
- leetcode Binary Tree Maximum Path Sum
- 【leetcode】Binary Tree Maximum Path Sum
- LeetCode - Binary Tree Maximum Path Sum
- [LeetCode]Binary Tree Maximum Path Sum
- [Leetcode]Binary Tree Maximum Path Sum
- Leetcode: Binary Tree Maximum Path Sum
- LeetCode-Binary Tree Maximum Path Sum
- [leetcode] Binary Tree Maximum Path Sum
- LeetCode - Binary Tree Maximum Path Sum
- LeetCode 124: Binary Tree Maximum Path Sum
- 【Leetcode】Binary Tree Maximum Path Sum
- LeetCode | Binary Tree Maximum Path Sum
- FI/CO模块的一些基本概念
- Tomcat7 采用service.bat 注册window服务
- LaTeX中算法环境设置
- rman中如何制定删除某段时间的归档日志
- 纯php多文件上传
- Binary Tree Maximum Path Sum (LeetCode)
- Ceres solver中几种常用算法介绍
- IOS源码分享
- 新浪微薄像个傻逼一样
- boost::bind函数原理和使用
- linux下创建和删除软、硬链接
- 【特别推荐】2013年最受欢迎的10篇前端开发博文
- ITL flag的含义
- SAP生产订单预留