-
Notifications
You must be signed in to change notification settings - Fork 624
Expand file tree
/
Copy pathinsertion_iterative.py
More file actions
47 lines (39 loc) · 862 Bytes
/
insertion_iterative.py
File metadata and controls
47 lines (39 loc) · 862 Bytes
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
class Node():
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert(root, val):
new_node = Node(val)
parent = None
curr = root
while curr:
parent = curr
if curr.val <= val:
curr = curr.right
else:
curr = curr.left
if parent.val <= val:
parent.right = new_node
else:
parent.left = new_node
def inorder(root):
if not root:
return None
stack = []
while True:
if root:
stack.append(root)
root = root.left
else:
if not stack:
break
root = stack.pop()
print(root.val, end=" ")
root = root.right
root = Node(4)
insert(root, 2)
insert(root, 6)
insert(root, 1)
insert(root, 8)
inorder(root)