Binary Tree Maximum Path Sum
Description
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
(Path sum is the sum of the weights of nodes on the path between two nodes.)
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: An integer
*/
//private TreeNode subTree = null ;
private int maxSum;
public int maxPathSum(TreeNode root) {
maxSum = Integer.MIN_VALUE;
findMax(root);
return maxSum;
}
private int findMax(TreeNode node) {
if (node == null) return 0;
int left = findMax(node.left);
int right = findMax(node.right);
maxSum = Math.max(node.val + left + right, maxSum);
int path = node.val + Math.max(left, right);
return Math.max(path, 0); //当某一端为负时,返回0.
}
}
该博客主要讨论如何解决一个计算机科学问题,即在给定的二叉树中找到最大的路径和。路径可以始于和终止于树中的任意节点,路径和是路径上所有节点值的总和。解决方案通过递归地遍历每个节点来计算左子树和右子树的最大路径,并更新全局最大路径和。关键在于理解如何有效地计算节点的最大贡献并处理负数的情况。
99

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



