Skip to content

Commit b4a932d

Browse files
authored
Create n-ary-tree-postorder-traversal.py
1 parent 1926289 commit b4a932d

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# Time: O(n)
2+
# Space: O(h)
3+
4+
# Given an n-ary tree, return the postorder traversal of its nodes' values.
5+
# For example, given a 3-ary tree:
6+
# Return its postorder traversal as: [5,6,3,2,4,1].
7+
# Note: Recursive solution is trivial, could you do it iteratively?
8+
9+
# Definition for a Node.
10+
class Node(object):
11+
def __init__(self, val, children):
12+
self.val = val
13+
self.children = children
14+
15+
16+
class Solution(object):
17+
def postorder(self, root):
18+
"""
19+
:type root: Node
20+
:rtype: List[int]
21+
"""
22+
if not root:
23+
return []
24+
result, stack = [], [root]
25+
while stack:
26+
node = stack.pop()
27+
result.append(node.val)
28+
for child in node.children:
29+
if child:
30+
stack.append(child)
31+
return result[::-1]
32+
33+
34+
class Solution2(object):
35+
def postorder(self, root):
36+
"""
37+
:type root: Node
38+
:rtype: List[int]
39+
"""
40+
def dfs(root, result):
41+
for child in root.children:
42+
if child:
43+
dfs(child, result)
44+
result.append(root.val)
45+
46+
result = []
47+
if root:
48+
dfs(root, result)
49+
return result

0 commit comments

Comments
 (0)