当前位置:网站首页>二叉树创建 & 遍历
二叉树创建 & 遍历
2022-07-06 07:40:00 【王吉吉丫】
层次创建
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = None
self.right = None
def creatTree(nodeList):
if nodeList[0] == None: return None
head = TreeNode(nodeList[0])
nodes = [head] # 用于存放树中的节点,每生成一个节点就将其放入该列表中,此处将根节点存入。
j = 1 # 创建变量j用于nodeList中元素的索引,初始为1.因为第0个元素已经创建根节点了。
for node in nodes: # 依次取出Nodes列表中的节点,对其创建左子节点和右子节点
if node != None:
node.left = (TreeNode(nodeList[j])) if nodeList[j] != None else None
nodes.append(node.left) # 将新建的节点加入Nodes数组,使其在for循环中可以继续为其添加子节点
j += 1
if j == len(nodeList): # 如果与nodeList值相等说明全部节点已经添加完毕了,直接返回head根节点就完成了树的建立
return head
node.right = (TreeNode(nodeList[j])) if nodeList[j] != None else None
j += 1
nodes.append(node.right)
if j == len(nodeList):
return head
a = [1,2,3,4,None,6,7]
a = creatTree(a)
# 使用:返回二叉树最长路径,Leecode 124
class Solution:
def __init__(self):
self.maxSum = float("-inf")
def maxPathSum(self, root: TreeNode) -> int:
def maxGain(node):
if not node:
return 0
leftGain = max(maxGain(node.left), 0)
rightGain = max(maxGain(node.right), 0)
priceNewpath = node.val + leftGain + rightGain
self.maxSum = max(self.maxSum, priceNewpath)
return node.val + max(leftGain, rightGain)
maxGain(root)
return self.maxSum
s = Solution()
s.maxPathSum(a)
Continue......
边栏推荐
猜你喜欢
Ble of Jerry [chapter]
Simulation of Michelson interferometer based on MATLAB
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
TypeScript接口与泛型的使用
Excel的相关操作
word中如何删除某符号前面或后面所有的文字
In the era of digital economy, how to ensure security?
Games101 Lesson 7 shading 1 Notes
烧录场景下的源代码防泄密方案分享
Solution: intelligent site intelligent inspection scheme video monitoring system
随机推荐
edge浏览器 路径获得
Opencv learning notes 8 -- answer sheet recognition
P3047 [USACO12FEB]Nearby Cows G(树形dp)
Qualitative risk analysis of Oracle project management system
Luogu p4127 [ahoi2009] similar distribution problem solution
After the hot update of uniapp, "mismatched versions may cause application exceptions" causes and Solutions
Methods for JS object to obtain attributes (. And [] methods)
链表面试题(图文详解)
word中把带有某个符号的行全部选中,更改为标题
剪映的相关介绍
Generator Foundation
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
Jerry's ad series MIDI function description [chapter]
TypeScript void 基础类型
leecode-C语言实现-15. 三数之和------思路待改进版
Brief explanation of instagram operation tips in 2022
How can word delete English only and keep Chinese or delete Chinese and keep English
Mise en œuvre du langage leecode - C - 15. Somme des trois chiffres - - - - - idées à améliorer
Vit (vision transformer) principle and code elaboration
Sharing of source code anti disclosure scheme under burning scenario