July 4, 2015
Problem statement:
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.
Blogs to read:
http://blog.unieagle.net/2012/12/09/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Abinary-tree-maximum-path-sum/
原来这讲解很清楚:
The best readable code, and
perfect to follow for this problem:
Julia's C#
practice.
Extension problem:
February 3, 2016
Review the algorithm, need
to figure out how to make this algorithm easy to remember, recall, write
without a bug.
Good analysis from the blog
(http://www.cnblogs.com/yuzhangcmu/p/4172855.html):
计算树的最长path有2种情况:
1.
通过根的path.
(1)如果左子树从左树根到任何一个Node的path大于零,可以链到root上
(2)如果右子树从右树根到任何一个Node的path大于零,可以链到root上
2.
不通过根的path. 这个可以取左子树及右子树的path的最大值。
所以创建一个inner class:
记录2个值:
1.
本树的最大path。
2.
本树从根节点出发到任何一个节点的最大path.
注意,当root == null,以上2个值都要置为Integer_MIN_VALUE;
因为没有节点可取的时候,是不存在solution的。以免干扰递归的计算
Practice using this class as return
type:
private class ResultType {
int singlePath;
int maxPath;
ResultType(int singlePath, int
maxPath) {
this.singlePath = singlePath;
this.maxPath = maxPath;
}
Read more blogs:
http://buttercola.blogspot.ca/2014/08/leetcode-binary-tree-maximum-path-sum.html
Discussion of global variable - max value - Julia likes the discussion https://leetcode.com/discuss/14190/accepted-short-solution-in-java |
No comments:
Post a Comment