124. Binary Tree Maximum Path Sum
# Hard, DFS
两个维度去分析这个问题
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int maxPath = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
pathHelper(root);
return maxPath;
}
public int pathHelper(TreeNode root) {
// stop condition
if(root == null) return Integer.MIN_VALUE;
int left = pathHelper(root.left);
int right = pathHelper(root.right);
int singlePath = Math.max(Math.max(left, right), 0) + root.val;
int rootPath = Math.max(left, 0) + Math.max(right, 0) + root.val;
maxPath = Math.max(Math.max(singlePath, rootPath), maxPath);
return singlePath;
}
}Last updated