4. L-sub + Node + R-sub (in here the max value cannot be passed to the parent) publicstaticintmaxPathSum(TreeNode root){int[] max = {Integer.MIN_VALUE};// 因为Java里都是pass by value所以利用数组传!rec(root, max);returnmax[0]; }publicstaticintrec(TreeNode root,int[] max){if...
returnmax(max(rootStartPathMaxSum(root->left)+root->val,rootStartPathMaxSum(root->right)+root->val),root->val); } }; 在小数据集上运行良好,但是一到大数据集就hold不住了,运行结果如下: 其实写的过程就意识到了rootStartPathMaxSum有很多次被重复调用,于是得采用一种自底向上的算法,自己想了半天...
maxGain 函数的返回值是给定节点 node 对其父节点路径的最大贡献值。 class Solution { int maxSum = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { maxGain(root); return maxSum; } public int maxGain(TreeNode node) { if (node == null) { return 0; } // 递归计算左右子节点的...
if not root: return -sys.maxsize # 求左子树的最大序列,且仅使用一个孩子节点(最后一层即叶节点) left = max(0, self.recursion(root.left)) # 求右子树的最大序列,且仅使用一个孩子节点(最后一层即也节点) right = max(0, self.recursion(root.right)) # 最终结果是可以取本节点的,于是我们取其...
self.maxSum=float('-inf')self._maxPathSum(root)returnself.maxSum def_maxPathSum(self,root):#DFSifroot is None:return0left=self._maxPathSum(root.left)right=self._maxPathSum(root.right)left=leftifleft>0else0right=rightifright>0else0self.maxSum=max(self.maxSum,root.val+left+right)# ...
defmaxPathSum(self,root:TreeNode)->int:self.dfs(root)returnself.res defdfs(self,root:TreeNode)->int:ifroot==None:return0l_max_sum=self.dfs(root.left)r_max_sum=self.dfs(root.right)sum=root.val sum=max(sum,sum+l_max_sum)sum=max(sum,sum+r_max_sum)self.res=max(self.res,sum)re...
*/publicclassSolution{privateintmax=Integer.MIN_VALUE;publicintmaxPathSum(TreeNoderoot){if(root==null)return0;dfs(root);returnmax;}privateintdfs(TreeNoderoot){if(root==null)return0;intleft=dfs(root.left);intright=dfs(root.right);int curr=root.val;int cmp=Math.max(left+curr,Math.max(rig...
public class MaxPathSum { public static void main(String[] strs) { TreeNode root = new TreeNode(2); TreeNode left = new TreeNode(-1); root.left = left; System.out.println(maxPathSum(root)); } public static class ReturnType { int maxSingle; int max; ReturnType (int maxSingle, ...
Leetcode 1004 Max Consecutive Ones III Leetcode 1658 Minimum Operations to Reduce X to Zero 宽度优先搜索(BFS):面试中最常考的 基础知识: 常见的BFS用来解决什么问题?(1) 简单图(有向无向皆可)的最短路径长度,注意是长度而不是具体的路径(2)拓扑排序(3) 遍历一个图(或者树) BFS基本模板(需要记录层...
public static int maxSubArray(int[] nums) { int Maxans = nums[0], Max = 0; for(int num : nums) { Max = Math.max(Max + num, num); Maxans = Math.max(Max, Maxans); } return Maxans; } 1. 2. 3. 4. 5. 6. 7.