# 124-二叉树最大路径和

Description:

Given a binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

For example:
Given the below binary tree,

Return 6.

class Solution {
int res = Integer.MIN_VALUE;

public int maxPathSum(TreeNode root) {
if(root == null)    return 0;

DFS(root);

return res;
}
public int DFS(TreeNode root){
if(root == null)    return 0;

int left = Math.max(0, DFS(root.left));
int right = Math.max(0, DFS(root.right));

res = Math.max(res, left + right + root.val);

return root.val + Math.max(left, right);
}
}

• 评论

• 上一篇
• 下一篇