Binary Tree Maximum Path Sum
来源:互联网 发布:淘宝省市区街道联动js 编辑:程序博客网 时间:2024/05/01 15:55
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
.
Analysis: For each node, there are total four possible ways to generate the max path sum.
a. The node itself.
b. The node itself plus left subtree.
c. The node itself plus right subtree.
d. The node itself plus left and right subtrees.
For each node, we should find the maximum value in these four cases and then compare with the current maximum value and update if necessary. Keep in mind that case d cannot be passed to the upper level node since it does not a qualified path. Therefore, we should find the maximum value among a, b and c and then return it back to the upper level node.
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public int maxPathSum(TreeNode root, int[] maxSum) { if(root==null) return 0; int leftSum = root.val+maxPathSum(root.left, maxSum); // root + left subtree int rightSum = root.val+maxPathSum(root.right, maxSum); // root + right subtree int totalSum = leftSum+rightSum-root.val; // root + left subtree + right subtree int nextMaxSum = Math.max(root.val, Math.max(leftSum, rightSum)); // max{left, right, self} int localMaxSum = Math.max(totalSum, nextMaxSum); // max{across, left, right, self} if(localMaxSum>maxSum[0]) maxSum[0]=localMaxSum; return nextMaxSum; } public int maxPathSum(TreeNode root) { int[] maxSum = new int[1]; maxSum[0] = Integer.MIN_VALUE; maxPathSum(root, maxSum); return maxSum[0]; }}
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- 锁和并发性----锁
- FreeSWITCH: JAVA模块的简单应用(mod_java)
- 使用Netbeans创建java Web项目
- CentOS 6.3 安装Apache
- Attachment
- Binary Tree Maximum Path Sum
- C#多线程学习(一) 多线程的相关概念
- Asp.net中防止用户多次登录的方法
- 小铁上初二的时候
- 又见回文
- 沉鱼
- C#多线程学习(二) 如何操纵一个线程
- 使用Netbeans创建java Web项目
- Xcode 5.0.2 如何显示、隐藏运行调试工具栏