描述
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 3Return 6.
分析
题目难度标了Hard,其实并不难,关键是要理解最长路径的构成。用深度优先遍历,对于每一个节点,都去考察以该节点为根,所能构成的最大半条路径,所谓半条路径就是指这条路径上的节点要么都在该节点的左子树,要么都在右子树,没有跨越的情况。这样一来,当前以当前节点为根的最长路径就是把左子树中最长半条路径和右子树的最长半条路径拼起来。
注意节点的值有可能是负数,所以,如果半条路径长是负值,我们就不要它。
代码
Python
1 | class Solution(object): |