[LeetCode]Binary Tree Maximum Path Sum
来源:互联网 发布:qownnotes软件 编辑:程序博客网 时间:2024/06/05 04:50
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
.
int sum = root.val; if(left>0) sum += left; if(right>0) sum += right; maxPath = Math.max(sum, maxPath);然后深搜每个节点,该节点返回的是这个节点的值加上较大的左子树或者较大的右子树
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution {int maxPath = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { dfs(root); return maxPath; } private int dfs(TreeNode root){ if(root==null) return 0; int left = dfs(root.left); int right = dfs(root.right); int sum = root.val; if(left>0) sum += left; if(right>0) sum += right; maxPath = Math.max(sum, maxPath); return Math.max(left, right)>0?root.val+Math.max(left, right):root.val; }}
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
- 黑马程序员——Objective-C 内存管理详解——黑马 IOS 技术博客
- 即时通讯架构研究
- 面向对象设计的工作步骤一:细化和重组类,细化和实现类间的关系明确可见性
- 2015蓝桥杯校内选拔C/C++组题1
- 【设计模式】对象行为—行为型模式和全部总结(大图)
- [LeetCode]Binary Tree Maximum Path Sum
- android 网络篇
- Sizeof与Strlen的区别与联系
- Android联动ListView的实现
- 自动化测试平台
- python迭代器、生成器和yield语句
- 解决libc.so.6: version `GLIBC_2.14' not found(或GLIBC_2.15)问题
- 【剑指Offer面试编程题】题目1503:二叉搜索树与双向链表--九度OJ
- 自然排序和强排序