【问题标题】:Binary Tree Preorder Traversal二叉树先序遍历
【发布时间】: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


【解决方案1】:

这是来自 leetcode 平台的problem,这是我的解决方案。运行时间:28 毫秒,比用于二叉树前序遍历的 Python3 在线提交的 81.08% 快。

class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        if not root:
            return []
        
        return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)
     

【讨论】:

  • 这不是迭代的
【解决方案2】:

你可以使用它的队列数据结构。

queue = []
result = []
queue.append(root)

while queue:
    node = queue.pop()
    result.append(node.val)

    if node.left is not None:
        queue.insert(0, node.left)

    if node.right is not None:
        queue.insert(0, node.right)

return result

【讨论】:

  • 您的代码描述了级别顺序遍历而不是预排序。
【解决方案3】:

几点:

  1. 函数preorderTraversal应该没有self参数;它不是一个类的方法。
  2. 我修改了TreeNode 类,以便更方便地指定其子TreeNode 对象。
  3. 函数preorderTraversal 将TreeNode 对象作为参数。正如我在评论中提到的,您的声明 #Input = [1,null, 2,3] 很难理解。
  4. 您需要保留未访问的 TreeNode 对象的后进/先出 (LIFO) stack 以实现迭代(而不是递归解决方案)。在下面的代码中,变量 nodes 用于此目的。

代码:

from typing import List

class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.x = val
        self.left = left
        self.right = right

n3 = TreeNode(3)
n2 = TreeNode(2, left=n3)
n1 = TreeNode(1, right=n2)

def preorderTraversal(root: TreeNode) -> List[int]:
    result = []
    nodes = []
    nodes.append(root) # initial node to visit
    while len(nodes): # any nodes left top visit?
        node = nodes.pop() # get topmost element, which is the next node to visit
        result.append(node.x) # "output" its value before children are visited
        if node.right is not None:
            # show this node must be visited
            nodes.append(node.right) # push first so it is popped after node.left
        if node.left is not None:
            # show this node must be visited
            nodes.append(node.left)
    return result

print(preorderTraversal(n1))

打印:

[1, 2, 3]

或者更复杂的树:

        10 
      /   \ 
    8      2 
  /  \    / 
3     5  2 

n3 = TreeNode(3)
n5 = TreeNode(5)
n8 = TreeNode(8, left=n3, right=n5)
n2a = TreeNode(2)
n2b = TreeNode(2, left=n2a)
n10 = TreeNode(10, left=n8, right=n2b)

print(preorderTraversal(n10))

打印:

[10, 8, 3, 5, 2, 2]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-08
    • 2021-03-08
    • 1970-01-01
    • 2012-01-01
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多