简体   繁体   中英

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

For a binary tree, we can traverse it in one line just like this (inorder, preorder, postorder is all ok):

# 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)

For a tree that has multi-child in its node, how to complete the traversal work in one line? I think list comprehension is a possible method, but I cannot complete the work in one line.

"""
# 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

Use a list comprehension to gather the traversal of all the root's children, regardless of how many children there are.

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)])

It could work like this:

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)]

The idea is that list comprehension replaces a repeated call to append , not to extend . The non-comprehension code, that maps to the above list comprehension version, is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM