-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
63 lines (52 loc) · 1.18 KB
/
main.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
63
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
# iterative
class Solution:
def preorderTraversal(self, root):
stack, res = [root], []
if not root: return res
while len(stack):
cur = stack.pop()
res.append(cur.val)
if cur.right: stack.append(cur.right)
if cur.left: stack.append(cur.left)
return res
# recursive
# class Solution:
# def preorderTraversal(self, node):
# res = []
#
# def traversal(node, res):
# if not node: return
#
# res.append(node.val)
# traversal(node.left, res)
# traversal(node.right, res)
#
# traversal(node, res)
#
# return res
# a
# / \
# b c
# / \ / \
# d e f g
a = TreeNode("a")
b = TreeNode("b")
c = TreeNode("c")
d = TreeNode("d")
e = TreeNode("e")
f = TreeNode("f")
g = TreeNode("g")
a.left = b
a.right = c
b.left = d
b.right = e
c.left = f
c.right = g
if __name__ == "__main__":
instance = Solution()
print(instance.preorderTraversal(a)) # ['a', 'b', 'd', 'e', 'c', 'f', 'g']