Binary Tree Maximum Path Sum
给一个二叉树, 问你path sum最大是多少, 返回最大值
遍历所有node, 如果当前的path sum小于0, 那么是对sum没帮助的, 只关心大于0的. 然后找到最大就行了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
int max = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { if(root == null) return 0; helper(root); return max; } public int helper(TreeNode root) { if (root == null) return 0; int left = Math.max(helper(root.left), 0); int right = Math.max(helper(root.right), 0); max = Math.max(max, root.val + left + right); return root.val + Math.max(left, right); } |
Leave A Comment