-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryTree.py
More file actions
57 lines (49 loc) · 1.13 KB
/
binaryTree.py
File metadata and controls
57 lines (49 loc) · 1.13 KB
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
# Binary Tree
# Uses python3
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
# Compare the new value with the parent node
if self.data:
if data < self.data:
if self.left:
self.left.insert(data)
else:
self.left = Node(data)
elif data > self.data:
if self.right:
self.right.insert(data)
else:
self.right = Node(data)
else:
self.data = data
def findval(self, val):
if self.data == val:
print(self.data,"found")
elif val < self.data:
if self.left.data == val:
print(val, "found")
return self.left.findval(val)
elif val > self.data:
if self.right.data == val:
print(val, "found")
return self.right.findval(val)
# Print the tree
def PrintTree(self):
if self.left:
self.left.PrintTree()
print(self.data)
if self.right:
self.right.PrintTree()
# Example of usage
if __name__ == "__main__":
root = Node(12)
root.insert(6)
root.insert(14)
root.insert(3)
print(root.findval(7))
print(root.findval(14))
root.PrintTree()