forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreorder.py
40 lines (34 loc) · 812 Bytes
/
preorder.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
'''
Time complexity : O(n)
'''
class Node:
""" This is a class of Node """
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def preorder(root):
""" Function to Preorder """
res = []
if not root:
return res
stack = []
stack.append(root)
while stack:
root = stack.pop()
res.append(root.val)
if root.right:
stack.append(root.right)
if root.left:
stack.append(root.left)
return res
def preorder_rec(root, res=None):
""" Recursive Implementation """
if root is None:
return []
if res is None:
res = []
res.append(root.val)
preorder_rec(root.left, res)
preorder_rec(root.right, res)
return res