-
Notifications
You must be signed in to change notification settings - Fork 220
/
Binary_tree.py
59 lines (50 loc) · 1.55 KB
/
Binary_tree.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
50
51
52
53
54
55
56
57
58
59
from node import Node
# Class of tree
class Tree:
def __init__(self):
self.root = None
# Method to obtain the data
def getRoot(self):
return self.root
# Method to add the data
def add(self, data):
if self.root is None:
self.root = Node(data)
else:
self._add(data, self.root)
def _add(self, data, node):
if data < node.data:
if node.left is not None:
self._add(data, node.left)
else:
node.left = Node(data)
else:
if node.right is not None:
self._add(data, node.right)
else:
node.right = Node(data)
# Method for find the data
def find(self, data):
if self.root is not None:
return self._find(data, self.root)
else:
return None
def _find(self, data, node):
if data == node.data:
return node
elif data < node.data and node.left is not None:
return self._find(data, node.left)
elif data > node.data and node.right is not None:
return self._find(data, node.right)
# Method for delete tree
def deleteTree(self):
self.root = None
# Method for print tree in terminal
def printTree(self):
if self.root is not None:
self._printTree(self.root)
def _printTree(self, node):
if node is not None:
self._printTree(node.left)
print(str(node.data) + " ")
self._printTree(node.right)