You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
Example 1:
Example 2:
这题我不会,看了大神的做法:
因为Java的基本数据类型是值传递,所以res不能作为参数,应该命名为属性。
采用后序遍历的方式,返回值是当前节点数值加上它的最大的子树路径,第二个参数记录res是以左子结点为终点的最大 path 之和加上以右子结点为终点的最大 path 之和,还要加上当前结点值,这样就组成了一个条完整的路径。
实际上这是树形DP的套路,不用创建新结构,从左子树收集信息,从右子树收集信息,在当前根节点处整合。不同的是整合后返回上一级的值跟总信息不同,前者代表一条非终结路径数值之和,后者时完整路径数值之和。
这段代码是在当前节点对左右信息的整合,获取最大路径。而下面一段代码返回的是取最大子树路径加上当前节点值,以便回溯上一级时作为一部分最大子树路径(变量left or right)。
还有一点,为什么要与0比较呢?
因为如果当前最大路径比0还小,那该路径不在选择之中,即路径选择一边就够了,而不是有折点的。如果左右两条路径都为负,那么选择根节点作为最大路径即可。比如二叉树根节点为1,左子树节点值为-1,右子树为-2,那么返回1。
Tips:
类似的多叉树树状DP求path问题:
参考资料:
The text was updated successfully, but these errors were encountered: