标签:
题目链接:https://leetcode.com/problems/binary-tree-maximum-path-sum/
题目:
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 does not need to go through the root.
For example:
Given the below binary tree,
1
/ 2 3
Return 6.
思路:
dfs递归,判断是否选择左右最大的分支,或者选择root结点。。
算法:
int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
dsp(root);
return max;
}
public int dsp(TreeNode root) {
if (root == null)
return 0;
int leftMax = dsp(root.left);// 左子树能返回的最大值
int rightMax = dsp(root.right);
max = Math.max(
Math.max(Math.max(
Math.max(leftMax + rightMax + root.val, rightMax
+ root.val), leftMax + root.val), max),
root.val);
return Math.max(Math.max(leftMax + root.val, rightMax + root.val),
root.val);
}
【Leetcode】Binary Tree Maximum Path Sum
标签:
原文地址:http://blog.csdn.net/yeqiuzs/article/details/51623540