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.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxPathSum(TreeNode root) {
int[] max = new int[1];
max[0] = Integer.MIN_VALUE;
solve(root, max);
return max[0];
}
private int solve(TreeNode root, int[] max) {
if (root == null) {
return 0;
}
int left = solve(root.left, max);
int right = solve(root.right, max);
int ans = Math.max(root.val, Math.max(root.val+left, root.val+right));
max[0] = Math.max(max[0], Math.max(ans, root.val+left+right));
return ans;
}
}
二叉树最大路径和算法
本文介绍了一种寻找给定二叉树中最大路径和的算法实现。该路径可以开始并结束于任意节点,通过递归遍历左子树和右子树,计算每个节点的最大贡献值,并维护全局最大路径和。
524

被折叠的 条评论
为什么被折叠?



