[LeetCode] 590. N-ary Tree Postorder Traversal_Easy
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 590. N-ary Tree Postorder Traversal_Easy相关的知识,希望对你有一定的参考价值。
Given an n-ary tree, return the postorder traversal of its nodes\' values.
For example, given a 3-ary
tree:
Return its postorder traversal as: [5,6,3,2,4,1]
.
这个题目思路就是跟LeetCode questions conlusion_InOrder, PreOrder, PostOrder traversal里面postorder traversal很像, 只是将left child 和right child变成了children而已,
当然这里假设的是children的顺序是从左到右的.
code
1) recursive
class Solution: def naryPostOrderTraversal(self, root): def helper(root): if not root: return for each in root.children: helper(each) ans.append(root.val) ans = [] helper(root) return ans
2) iterable
class Solution: def naryPostOrderTraversal(self, root): if not root: return [] stack, ans = [(root, False)], [] while stack: node, visited = stack.pop() if visited: ans.append(node.val) else: stack.append((node, True)) for each in node.children[::-1]: stack.append((each, False)) return ans
以上是关于[LeetCode] 590. N-ary Tree Postorder Traversal_Easy的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode&Python] Problem 590. N-ary Tree Postorder Traversal
leetcode590. N-ary Tree Postorder Traversal
(N叉树 递归) leetcode 590. N-ary Tree Postorder Traversal
[LeetCode] 590. N-ary Tree Postorder Traversal_Easy