【发布时间】:2022-01-11 09:22:32
【问题描述】:
我无法理解我的代码有什么问题并理解下面的约束。
我的伪代码:
- 遍历树的 Level Order 并构造数组表示(输入实际上是作为单个根给出的,但它们使用数组表示来显示完整的树)
- 遍历此数组表示,跳过空节点
- 对于每个节点,我们称其为 X,向上迭代直到到达根节点,检查路径中是否有任何点,
parentNode > nodeX,这意味着 nodeX 不是一个好节点。 - 如果节点正常则增加计数器
约束:
- 二叉树的节点数在 [1, 10^5] 范围内。
- 每个节点的值都在 [-10^4, 10^4] 之间
首先:
我对约束的困惑是,自动化测试正在提供诸如[2,4,4,4,null,1,3,null,null,5,null,null,null,null,5,4,4] 之类的输入,如果我们遵循孩子位于c1 = 2k+1 和c2 = 2k+2 和parent = (k-1)//2 的规则,那么这意味着存在具有值@ 的节点987654329@
其次: 对于上面的输入,我的代码输出8,期望值是6,但是当我从数组中画树的时候,我也觉得答案应该是8!
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def goodNodes(self, root: TreeNode) -> int:
arrRepresentation = []
queue = []
queue.append(root)
# while queue not empty
while queue:
# remove node
node = queue.pop(0)
if node is None:
arrRepresentation.append(None)
else:
arrRepresentation.append(node.val)
if node is not None:
# add left to queue
queue.append(node.left)
# add right to queue
queue.append(node.right)
print(arrRepresentation)
goodNodeCounter = 1
# iterate over array representation of binary tree
for k in range(len(arrRepresentation)-1, 0, -1):
child = arrRepresentation[k]
if child is None:
continue
isGoodNode = self._isGoodNode(k, arrRepresentation)
print('is good: ' + str(isGoodNode))
if isGoodNode:
goodNodeCounter += 1
return goodNodeCounter
def _isGoodNode(self, k, arrRepresentation):
child = arrRepresentation[k]
print('child: '+str(child))
# calculate index of parent
parentIndex = (k-1)//2
isGood = True
# if we have not reached root node
while parentIndex >= 0:
parent = arrRepresentation[parentIndex]
print('parent: '+ str(parent))
# calculate index of parent
parentIndex = (parentIndex-1)//2
if parent is None:
continue
if parent > child:
isGood = False
break
return isGood
【问题讨论】:
-
你应该从问题陈述开始。如果没有这种上下文,您的混淆或伪代码对读者来说意义不大。
-
至于第二个问题,我觉得你画错了树。直到第三级(即,4、1、3),树是正确的。但那一定是 5 是 1 的孩子,然后另一个 5 是这个 5 的孩子。那么 4 和 4 是最后 5 的孩子。
-
表示树的数组称为二叉堆。空条目表示没有子项(不是该值为空)。看这里:en.wikipedia.org/wiki/Heap_(data_structure)
标签: python algorithm tree binary-tree breadth-first-search