LeetCode 124. Binary Tree Maximum Path Sum
来源:互联网 发布:东华软件待遇怎么样 编辑:程序博客网 时间:2024/06/05 11:10
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 must contain at least one node and does not need to go through the root.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6.
求二叉树任意起止点构成的路径的值最大和
虽然是任意起止点,但此路径一定会有根节点,因此对于该根节点:
max = root.val+maxPathSum(左子树)(>0才加)+maxPathSum(右子树)(>0才加);
但对于每次递归的返回,则应该是
return max(root.val,root.val+maxPathSum(左子树),root.val+maxPathSum(右子树));
public static int max; public static int maxPathSum(TreeNode root) { if(root==null) return 0; max = Integer.MIN_VALUE; maxPathSum2(root); return max; } public static int maxPathSum2(TreeNode root) { if(root==null) return 0; int temp1 = maxPathSum2(root.left); int temp2 = maxPathSum2(root.right); int temp = root.val; if(temp1>0)temp+=temp1; if(temp2>0)temp += temp2; max = temp>max?temp:max; return max(root.val,root.val+temp1,root.val+temp2); } public static int max(int i,int j,int k){ return i > (j>k?j:k) ? i : (j>k?j:k); }
阅读全文
0 0
- LeetCode 124. Binary Tree Maximum Path Sum
- [LeetCode]*124.Binary Tree Maximum Path Sum
- [Leetcode] 124. Binary Tree Maximum Path Sum
- [leetcode] 124. Binary Tree Maximum Path Sum
- [leetcode] 124. Binary Tree Maximum Path Sum
- Leetcode 124. Binary Tree Maximum Path Sum
- Leetcode 124. Binary Tree Maximum Path Sum
- LeetCode 124. Binary Tree Maximum Path Sum
- leetcode 124. Binary Tree Maximum Path Sum
- LeetCode 124. Binary Tree Maximum Path Sum
- Leetcode 124. Binary Tree Maximum Path Sum
- [LeetCode] 124. Binary Tree Maximum Path Sum
- leetcode 124.Binary Tree Maximum Path Sum
- leetcode-124. Binary Tree Maximum Path Sum
- [LeetCode]124. Binary Tree Maximum Path Sum
- Leetcode 124. Binary Tree Maximum Path Sum
- LeetCode 124. Binary Tree Maximum Path Sum
- LEETCODE 124. Binary Tree Maximum Path Sum
- 多个框架问题的自我整理与理解
- Unity 富文本的使用
- Android日期格式和字符串格式相互转换
- 举例说明了十大ES6功能
- 借助eclipse的DDMS来分析线程执行情况
- LeetCode 124. Binary Tree Maximum Path Sum
- ajax调用mvc action使用实体参数
- Web Uploader插件
- 《c语言程序设计》例 3-1 3-2 3-3 3-5 3-6 3-7 3-8 3-9 3-10 3-11
- BIM软件工具选择顺手——事半功倍
- jquery 滚动列表
- HighChart的动态添加元素问题
- Untiy使用NetworkDiscorver创建 局域网 房间
- 好久没有写博客了,写一下刚学的