首页 > 编程语言 > 详细

[LeetCode&Python] Problem 589. N-ary Tree Preorder Traversal

时间:2018-10-05 13:24:55      阅读:245      评论:0      收藏:0      [点我收藏+]

Given an n-ary tree, return the preorder traversal of its nodes‘ values.

 

For example, given a 3-ary tree:

技术分享图片

 

Return its preorder traversal as: [1,3,5,6,2,4].

 

Note: Recursive solution is trivial, could you do it iteratively?

 

Recursion Method:

"""
# Definition for a Node.
class Node(object):
    def __init__(self, val, children):
        self.val = val
        self.children = children
"""
class Solution(object):
    def preorder(self, root):
        """
        :type root: Node
        :rtype: List[int]
        """
        l=[]
        
        def subpreorderfun(r):
            if r:
                l.append(r.val)
                for c in r.children:
                    subpreorderfun(c)
        
        subpreorderfun(root)
        
        return l

  

Iteration Method:

"""
# Definition for a Node.
class Node(object):
    def __init__(self, val, children):
        self.val = val
        self.children = children
"""
class Solution(object):
    def preorder(self, root):
        """
        :type root: Node
        :rtype: List[int]
        """
        l=[]
        q=[root]
                
        if root:
            p=[]
            while q:
                a=q.pop(0)
                l.append(a.val)
                
                for c in a.children:
                    p.append(c)
                    
                n=len(p)
                for i in range(n):
                    q=[p.pop()]+q
                
        return l

  

[LeetCode&Python] Problem 589. N-ary Tree Preorder Traversal

原文:https://www.cnblogs.com/chiyeung/p/9744423.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!