Maximum Path Sum Binary Tree
Laicode: https://app.laicode.io/app/problem/138 二叉树任意两个leaf node的最大路径和
Link
Laicode: https://app.laicode.io/app/problem/138
https://app.laicode.io/app/problem/140
Given a binary tree in which each node contains an integer number. Find the maximum possible sum from one leaf node to another leaf node. If there is no such path available, return Integer.MIN_VALUE(Java)/INT_MIN (C++).
Examples
-15
/ \
2 11
/ \
6 14
The maximum path sum is 6 + 11 + 14 = 31.
How is the binary tree represented?
We use the level order traversal sequence with a special symbol "#" denoting the null node.
For Example:
The sequence [1, 2, 3, #, #, 4] represents the following binary tree:
1
/ \
2 3
/
4
想法: top-down (更新global max) + bottom up(返回从上往下的path的最大的sum)
把每个node遍历一遍
在每个node里面,找到left 的path sum和right path sum(如果存在), 并把left path, right path node.val相加得到最远的两个leaf node的path的sum
对比这个path sum和global max,更新global max
返回加上当前的node.val的一条在root node到leaf node的path上面的最大的path,即max(left,right)+node.val,就返回当前最大的single path
Source Code
Last updated