簡體   English   中英

如何遍歷只有一條線的樹? (python,樹遍歷)

[英]How to traverse a tree with only one line? (python, tree traversal)

對於二叉樹,我們可以像這樣在一行中遍歷它(inorder, preorder, postorder 都可以):

# 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

# this is a preorder traversal with one line:

class Solution:
    def preorderTraversal(self, root) -> List[int]:
        return [] if root is None else [r.val] + self.preorderTraversal(r.left) + self.preorderTraversal(r.right)

對於一個節點中有多個子節點的樹,如何一行行完成遍歷工作? 我認為列表理解是一種可能的方法,但我無法一口氣完成工作。

"""
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""
class Solution:
    def preorder(self, root: 'Node') -> List[int]:
        if root is None: return []
        ans = [root.val]
        [ans.extend(x) for x in [self.preorder(child) for child in root.children]]
        return ans

# This is a normal traversal:
# class Solution:
#     def preorder(self, root: 'Node') -> List[int]:
#         if root is None: return []
#         ans = [root.val]
#         for child in root.children:
#             ans += self.preorder(child)
#         return ans

使用列表推導來收集所有根的孩子的遍歷,不管有多少孩子。

class Solution:
    def preorderTraversal(self, root) -> List[int]:
        # Original hard-coded approach for binary trees
        # return [] if root is None else [r.val] \
        #   + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)

        # Generalized approach for binary trees
        # return [] if root is None else [r.val] \
        #   + [y for child in [root.left, root.right] for y in self.preorderTraversal(child)]

        # Generalized approach for a tree with arbitrary children per node
        return [] if root is None else ([root.val]
          + [y for child in root.children for y in self.preorderTraversal(child)])

它可以像這樣工作:

class Solution:
    def preorder(self, root):
        return [] if root is None else [root.val] + [value 
            for child in (root.children or []) 
                for value in self.preorder(child)]

這個想法是列表理解取代了對append的重復調用,而不是extend 映射到上述列表理解版本的非理解代碼是:

class Solution:
    def preorder(self, root):
        if root is None:
            return []
        res = [root.val]
        for child in (root.children or []):
            for value in self.preorder(child):
                res.append(value)
        return res

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM