classSolution{ int maxvalue = Integer.MIN_VALUE; publicintmaxPathSum(TreeNode root){ dfs(root); return maxvalue; } publicintdfs(TreeNode node){ if (node == null) return0; int left = dfs(node.left); int right = dfs(node.right); left = left < 0 ? 0 : left; right = right < 0 ? 0 : right; maxvalue = Math.max(maxvalue, left + right + node.val); return Math.max(left, right) + node.val; } }
1 2 3 4 5 6
bottom up general steps: 1. Base case 2. 向子问题要答案 3. 利用子问题构建当前答案 4. 额外操作 5. 返回答案给父问题