Leetcode: maximum path sum in binary tree (Python)

A good function 2020-11-13 02:57:08
leetcode maximum path sum binary

1. Title Description

Given a non empty binary tree , Return its maximum path and .
In this question , The path is defined as a starting point from any node in the tree , A sequence that reaches any node . The path contains at least one node , And it doesn't have to go through the root node .

Example 1:
Input : [1,2,3]

/ \
2 3

Output : 6

Example 2:
Input : [-10,9,20,null,null,15,7]

/ \
9 20
/ \
15 7

Output : 42

2. Ideas

For any node , If the maximum and path contain the node , Then there are only two cases :

  1. The one with the larger path value in the left and right subtrees ( If the maximum path sum of left or right subtrees is negative , Set to zero , Indicates that the maximum path does not pass through this subtree ) Add the value of the node and backtrack to the parent node to form the maximum path , There may not be left or right subtrees , Only the value of this node goes back .
  2. Left and right subtrees are in the maximum path , Add the value of this node to form the final maximum path . namely , This node is the root of the maximum path .

2.1 python Code

# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self): # Define a result attribute 
self.result = float("-inf")
def maxPathSum(self, root: TreeNode) -> int:
if root == None:
return 0
return self.result
def getMax(self,root): # Define an auxiliary function 
if root == None: # If the current node is empty, the maximum path containing the current node is 0
return 0
# Recursively calculates the maximum path and the path provided by the left and right subtrees of the current node , If a negative , Set it to zero ( and 0 Compare )
left = max(0,self.getMax(root.left))
right = max(0,self.getMax(root.right))
# Calculate the maximum value of left and right subtrees every time , Just update the current result
self.result = max(self.result,left + right + root.val)
# Back to the parent node , The maximum path cannot contain two subtrees at the same time ,
# So we need to use the larger subtree of the left and right subtrees plus the value of the current node for backtracking 
return max(left,right) + root.val
#( Recursive function , What is returned is the formula needed for backtracking , Instead of returning the final result ( Like here return result))

ps: A little recursive understanding ( Seek correction )

Backtracking can often be realized by returning , When using recursive functions ,return It's not the result of function implementation
It's going back to the formula needed to go to the top ( Most of the final results are the same as those needed for backtracking ), It may not be the final function of this function . The formula needed to go back , Take this topic for example , In defining getMax Function , What we're returning to is max(left,right)+ root.val, Because if you go back from the current node to the upper parent node , It is necessary to provide the maximum path and... Composed of the current node and a certain subtree for the upper node . And the end result result It is in the process of recursion that it is constantly updated as a function return.

本文为[A good function]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database