Problem Description:
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1 / 2 3
Return 6
.
Solution:
1 public class Solution { 2 public int max; 3 public int maxPathSum(TreeNode root) { 4 if (root == null) return 0; 5 max = root.val; 6 findMax(root); 7 return max; 8 } 9 public int findMax(TreeNode node) { 10 if (node == null) return 0; 11 12 int left = Math.max(findMax(node.left), 0); 13 int right = Math.max(findMax(node.right), 0); 14 15 max = Math.max(node.val + left + right, max); 16 17 return node.val + Math.max(left, right); 18 } 19 }
Problem Binary Tree Maximum Path Sum
时间: 2024-11-06 22:49:19