活跃农民
- 积分
- 609
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-2-15
- 最后登录
- 1970-1-1
|
- private static int max = Integer.MIN_VALUE;
- private static int maxPathSum(TreeNode root) {
- dfs(root);
- return max;
- }
-
- // Use Integer as return type to distinguish between a true MIN_VALUE or it's null
- public static Integer dfs(TreeNode node) {
- if (node == null)
- return null;
- // find the alive node, return its value
- if (node.left == null && node.right == null && node.hasAst) {
- return node.val;
- }
- int val = node.val;
- Integer left = dfs(node.left);
- Integer right = dfs(node.right);
- // if both children are not null, means we find a path that travels from one alive node to another
- if (left != null && right != null) {
- max = Math.max(max, left + val + right);
- }
- Integer leftMax = left == null ? null : left + val;
- Integer rightMax = right == null ? null : right + val;
- // if either leftMax or rightMax is null, it means one of these path is not leading to an alive node, so return the non null path max
- if (leftMax == null || rightMax == null)
- return leftMax != null ? leftMax : rightMax;
- return Math.max(leftMax, rightMax);
- }
复制代码 |
|