[LeetCode&Python] Problem 590. N-ary Tree Postorder Traversal
2021-06-15 21:04
标签:values finish children post alt code iter strong etc Given an n-ary tree, return the postorder traversal of its nodes‘ values. For example, given a Return its postorder traversal as: Note: Recursive solution is trivial, could you do it iteratively? Recursion Solution: Iteration Solution: [LeetCode&Python] Problem 590. N-ary Tree Postorder Traversal 标签:values finish children post alt code iter strong etc 原文地址:https://www.cnblogs.com/chiyeung/p/9728816.html3-ary
tree:[5,6,3,2,4,1]
."""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def postorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
def dfs(r):
if not r:
return
else:
for c in r.children:
dfs(c)
result.append(r.val)
result=[]
dfs(root)
return result
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def postorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if not root:
return []
# We can use a deque to store the solution
res=collections.deque()
# We use stack to store all the node
#Every time, we only need to pick the top node in the stack
#and store its value in res
#And then we store its children in the stack. The right-most
#child is stored in the top.
#If our stack is empty, we finish our job.
stack=[root]
while stack:
u=stack.pop()
res.appendleft(u.val)
for c in u.children:
stack.append(c)
#change deque back to list
return list(res)
上一篇:python递归
下一篇:使用多线程制作双色球
文章标题:[LeetCode&Python] Problem 590. N-ary Tree Postorder Traversal
文章链接:http://soscw.com/index.php/essay/94286.html