【发布时间】:2020-01-15 22:34:00
【问题描述】:
我刚刚开始使用二叉树,我有这个任务,我必须对给定的二叉树“[1,null,2,3]”进行前序迭代遍历搜索。
我尝试使用我发现的一个新的二叉树模块,但没有成功,我看到了一个 youtube 视频,其中有人递归地做了,但我就是想不通。
#Input = [1,null, 2,3]
# 1
# \
# 2
# /
# 3
#Expected output = [1,2,3]
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
我只是一无所知,我写了一个算法,但我不能把它变成实际的功能代码。我也不明白 root: TreeNode 是如何工作的。它是否将列表中的每个元素都转换为 TreeNode 对象?到目前为止,我最好的尝试是这个,它在很多方面显然是错误的。
def preorderTraversal(self, root: TreeNode) -> List[int]:
result = []
for i in root:
if i =! root[0] and root.left =! None:
root.left = i
if root.left =! null:
root.left.left = i
elif root.left == null:
root.right.left = i
elif root.left
result.append(i)
elif root.right == None:
root.right = i
else:
continue
【问题讨论】:
-
[1, null, 2, 3]是什么意思?顺便说一句,null在 Python 中没有特别的意义。
标签: python iteration binary-tree preorder