[LeetCode&Python] Problem 589. N-ary Tree Preorder Traversal
2021-05-18 12:28
标签:turn note ima set 分享 images end solution tps Given an n-ary tree, return the preorder traversal of its nodes‘ values. For example, given a Return its preorder traversal as: Note: Recursive solution is trivial, could you do it iteratively? Recursion Method: Iteration Method: [LeetCode&Python] Problem 589. N-ary Tree Preorder Traversal 标签:turn note ima set 分享 images end solution tps 原文地址:https://www.cnblogs.com/chiyeung/p/9744423.html3-ary
tree:[1,3,5,6,2,4]
."""
# 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
"""
# 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
文章链接:http://soscw.com/essay/87185.html