当前位置:网站首页>LeetCode 124. Binary tree maximum path sum - binary tree series question 8
LeetCode 124. Binary tree maximum path sum - binary tree series question 8
2022-06-27 16:48:00 【CP Coding】
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.
The path sum of a path is the sum of the node's values in the path.
Given the root of a binary tree, return the maximum path sum of any non-empty path.
Example 1:

Input: root = [1,2,3] Output: 6 Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.
Example 2:

Input: root = [-10,9,20,null,null,15,7] Output: 42 Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.
Constraints:
- The number of nodes in the tree is in the range
[1, 3 * 104]. -1000 <= Node.val <= 1000
A path in a binary tree path Defined , A path is a sequence of nodes , Adjacent nodes are connected by an edge , Each node can only appear once in the path , The path does not have to go through the root node , It doesn't have to start or end with a leaf node . Path sum is the sum of all node values in the path . It is required to find the largest path in the tree and .
According to the above description of the path , We can know that for a node , The path with the maximum path sum passing through the node is one of the following paths :
1) Node itself , That is, the path has only one node
2) Node itself + The path with the largest sum from the left child node down
3) Node itself + The path with the largest sum from the right child node down
4) The path with the largest sum from the left child node down + Node itself + The path with the largest sum from the right child node down .
above 4 The path with the largest sum is the maximum sum path passing through that node , So find the maximum sum path of all nodes , Then find out the maximum path in the whole tree .
So we can use the following sequence to go through the calendar , When traversing a node , First, recursively call and wait for the left subtree to return the path with the maximum sum from the left subtree , Then recursively call and wait for the right subtree to return the path with the maximum sum from the right subtree , Then we can calculate the above described 4 The sum of the paths , Find the maximum sum . Finally, we have to put “ Node itself + The path with the largest sum from the left child node down ” and “ Node itself + The path with the largest sum from the right child node down ” The larger of is returned to the upper layer for use .
class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
maxSum = -1000
def helper(node):
if not node:
return 0
nonlocal maxSum
lsum = helper(node.left)
rsum = helper(node.right)
maxSum = max(maxSum, lsum + rsum + node.val)
res = max(max(lsum + node.val, rsum + node.val), node.val)
maxSum = max(maxSum, res)
return res
helper(root)
return maxSum边栏推荐
- 利用Redis实现订单30分钟自动取消
- Unity 阴影——阴影平坠(Shadow pancaking)
- The interview lasted for half a year. Last month, I successfully got Alibaba p7offer. It was all because I chewed the latest interview questions in 2020!
- What are the password requirements for waiting insurance 2.0? What are the legal bases?
- QT5 之信号与槽机制(信号与槽的基本介绍)
- National food safety risk assessment center: do not blindly and unilaterally pursue "zero addition" and "pure natural" food
- 【Pygame小游戏】这款“吃掉一切”游戏简直奇葩了?通通都吃掉嘛?(附源码免费领)
- Adaoracle supports multi chain distributed Oracle with wide area node quotation
- 跨域图像的衡量新方式Style relevance:论文解读和代码实战
- Special function calculator
猜你喜欢

Hierarchical clustering and case analysis

如何提升IT电子设备效能管理

Leetcode daily practice (longest substring without repeated characters)

What is the level 3 password complexity of ISO? How often is it replaced?

Alibaba cloud liupeizi: Inspiration from cloud games - innovation on the end

Sliding window + monotone queue concept and example (p1886 Logu)
![[Niuke's questions] nowcoder claims to have remembered all Fibonacci numbers between 1 and 100000. To test him, we gave him a random number N and asked him to say the nth Fibonacci number. If the nth](/img/70/fa79ba38e28c41ed28bce2ec73cd79.png)
[Niuke's questions] nowcoder claims to have remembered all Fibonacci numbers between 1 and 100000. To test him, we gave him a random number N and asked him to say the nth Fibonacci number. If the nth

After the mobile phone, it was reported that Samsung also cut the output of TV and other home appliance product lines

树莓派初步使用

阿里云刘珅孜:云游戏带来的启发——端上创新
随机推荐
QT5 之信号与槽机制(信号与槽的基本介绍)
Yyds dry inventory solution sword finger offer: a path with a certain value in the binary tree (3)
[pygame Games] ce jeu "eat Everything" est fantastique? Tu manges tout? (avec code source gratuit)
The array of C language is a parameter to pass a pointer
Leetcode daily practice (sum of two numbers)
Realize simple three-D cube automatic rotation
实现简单的三D立方体自动旋转
Introduce you to ldbc SNB, a powerful tool for database performance and scenario testing
tensorflow求解泊松方程
EMQ helps Qingdao Yanbo build a smart water platform
2022年中国音频市场年度综合分析
C語言教師工作量管理系統
#yyds干货盘点# 解决剑指offer:二叉树中和为某一值的路径(三)
What are the password requirements for waiting insurance 2.0? What are the legal bases?
郎酒两大王牌产品成都联动共振,持续带动光瓶酒消费浪潮
10 minutes to master the installation steps of MySQL
IDE Eval reset unlimited trial reset
【Pygame小遊戲】這款“吃掉一切”遊戲簡直奇葩了?通通都吃掉嘛?(附源碼免費領)
Hung - Mung! HDD Hangzhou station · salon hors ligne vous invite à construire l'écologie
Handling of difficult and miscellaneous problems during the installation and configuration of qt5.5.1 desktop version (configuring arm compilation Kit)