leetCode练习(124)
来源:互联网 发布:linux用户和组管理 编辑:程序博客网 时间:2024/04/28 01:15
题目:Binary Tree Maximum Path Sum
难度:hard
问题描述:
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 does not need to go through the root.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6
.
解题思路:
通过递归,求解每个经过最高层节点n的最大值。经过‘1’节点的最大值=1+1.left的单边最大值+1.right的单边最大值。也就是说,对于节点n,其返回值为n.val加上其中一条边或者0条边的值。同时设置全局变量保存每各经过的最高层节点路径和中的最大者。
代码如下:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { private int res=Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { maxsum(root);return res; } private int maxsum(TreeNode root){if(root==null) return Integer.MIN_VALUE;int left=maxsum(root.left);int right=maxsum(root.right);if(root.val>=0){if(left>0){if(right>0){res=Math.max(res, root.val+left+right);}else{res=Math.max(res, root.val+left);}}else{if(right>0){res=Math.max(res, root.val+right);}else{res=Math.max(res, root.val);}}}else{//root<0if(left>0){if(right>0){res=Math.max(res,root.val+left+right);}else{res=Math.max(res, left);}}else{if(right>0){res=Math.max(res, root.val+right);}else{res=Math.max(res,root.val);}}}return Math.max(root.val+Math.max(0, left), root.val+Math.max(0, right));}}
0 0
- leetCode练习(124)
- leetCode练习(7)
- leetCode练习(9)
- leetCode练习(2)
- leetCode练习(14)
- leetCode练习(3)
- leetCode练习(4)
- leetCode练习(19)
- leetCode练习(18)
- leetCode练习(5)
- leetCode练习(15)
- leetCode练习(20)
- leetCode练习(21)
- leetCode练习(16)
- leetCode练习(17)
- leetCode练习(11)
- leetCode练习(24)
- leetCode练习(22)
- 微信小程序开放公测
- Android固定宽度文字自适应大小
- unix环境高级编程--进程环境与进程控制
- MySql学习存储过程遇到的问题
- 关于刷机的一些感悟
- leetCode练习(124)
- 第十周项目1-二叉树算法库
- 黑马程序员前端与移动开发学院2.0课程震撼来袭!
- js 匿名函数和闭包函数
- MySQL主机127.0.0.1与localhost区别总结
- 【日常问题】log4j无法通过jvm参数指定配置文件的问题
- 定义结构体与分配内存
- 老程序员的python快速学习之旅
- 【文智背后的奥秘】系列篇——关键词智能提取