-
Notifications
You must be signed in to change notification settings - Fork 7
/
solution.py
39 lines (37 loc) · 981 Bytes
/
solution.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
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def preorderTraversal_1(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
"""
Recursive Traversal, trivial
"""
if root is None:
return []
left = self.preorderTraversal(root.left)
right = self.preorderTraversal(root.right)
return [root.val] + left + right
class Solution(object):
def preorderTraversal_2(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
"""
Iterative Traversal
"""
res = []
stack = [root]
while stack:
node = stack.pop()
if node:
stack.extend([node.right, node.left])
res.append(node.val)
return res