LeetcodeBinary Tree Maximum Path Sum
Posted wuezs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetcodeBinary Tree Maximum Path Sum相关的知识,希望对你有一定的参考价值。
题目链接: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);
}
以上是关于LeetcodeBinary Tree Maximum Path Sum的主要内容,如果未能解决你的问题,请参考以下文章
LeetCodeBinary Tree Level Order Traversal BFS
leetcodeBinary Tree Level Order Traversal