-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path589.N-ary-Tree-Preorder-Traversal.py
62 lines (47 loc) · 1.16 KB
/
589.N-ary-Tree-Preorder-Traversal.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# https://leetcode.com/problems/n-ary-tree-preorder-traversal/description/
#
# algorithms
# Easy (59.56%)
# Total Accepted: 8.1k
# Total Submissions: 13.6k
# beats 97.77% of python submissions
"""
# 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]
"""
res = [[]]
def resursive(node):
if not node:
return
res[0] += node.val,
for child in node.children:
resursive(child)
resursive(root)
return res[0]
from collections import deque
class Solution1(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if not root:
return []
q = deque([root])
res = []
while q:
node = q.pop()
res.append(node.val)
if node.children:
for n in reversed(node.children):
q.append(n)
return res