-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPreorderTraversal.py
49 lines (31 loc) · 1.04 KB
/
PreorderTraversal.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
import collections
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def iterativePreorderTraversal(root: TreeNode) -> list[int]:
traversal_queue = collections.deque()
if type(root) is TreeNode:
traversal_queue.append(root)
else:
return []
traversal = []
while traversal_queue:
current = traversal_queue.popleft()
if type(current.right) is TreeNode:
traversal_queue.appendleft(current.right)
if type(current.left) is TreeNode:
traversal_queue.appendleft(current.left)
traversal.append(current.val)
return traversal
def recursivelyPreorderTraversal(root: TreeNode):
if type(root) is not TreeNode:
return None
result = [root.val]
if type(root.left) is TreeNode:
result += recursivelyPreorderTraversal(root.left)
if type(root.right) is TreeNode:
result += recursivelyPreorderTraversal(root.right)
return result