首页 > 其他 > 详细

LeetCode | Binary Tree Maximum Path Sum

时间:2014-02-24 03:16:06      阅读:352      评论:0      收藏:0      [点我收藏+]

题目

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.

分析

通过不断递归左右子树进行求解,需要求出左右子树的Maximum Path Sum,同时,为了求出当前节点的Maximum Path Sum,还需要记录子树中包含子树根节点(能与当前节点联通)的并且拥有Maximum Sum的“树枝”。

代码

public class BinaryTreeMaximumPathSum {
	public class TreeNode {
		int val;
		TreeNode left;
		TreeNode right;

		TreeNode(int x) {
			val = x;
		}
	}

	class Result {
		int maxPathSum;
		int maxSingleBranchSum;
	}

	private Result solve(TreeNode root) {
		Result result = new Result();
		if (root.left == null && root.right == null) {
			result.maxPathSum = root.val;
			result.maxSingleBranchSum = root.val;
			return result;
		}
		// get max path sum & max single branch sum
		int maxPathSum = root.val;
		int maxSingleBranchSum = root.val;
		Result leftResult = null;
		Result rightResult = null;
		if (root.left != null) {
			leftResult = solve(root.left);
			if (leftResult.maxSingleBranchSum > 0) {
				maxPathSum += leftResult.maxSingleBranchSum;
				maxSingleBranchSum += leftResult.maxSingleBranchSum;
			}
		}
		if (root.right != null) {
			rightResult = solve(root.right);
			if (rightResult.maxSingleBranchSum > 0) {
				maxPathSum += rightResult.maxSingleBranchSum;
				maxSingleBranchSum = Math.max(maxSingleBranchSum, root.val
						+ rightResult.maxSingleBranchSum);
			}
		}
		if (leftResult != null) {
			maxPathSum = Math.max(maxPathSum, leftResult.maxPathSum);
		}
		if (rightResult != null) {
			maxPathSum = Math.max(maxPathSum, rightResult.maxPathSum);
		}
		result.maxPathSum = maxPathSum;
		result.maxSingleBranchSum = maxSingleBranchSum;
		return result;
	}

	public int maxPathSum(TreeNode root) {
		if (root == null) {
			return Integer.MIN_VALUE;
		}
		return solve(root).maxPathSum;
	}
}



LeetCode | Binary Tree Maximum Path Sum

原文:http://blog.csdn.net/perfect8886/article/details/19754551

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!