In this article we will learn about some of the frequently asked Python programming questions in technical like “binary search tree in python” Code Answer’s. When creating scripts and web applications, error handling is an important part. If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks. Error handling in Python is simple. An error message with filename, line number and a message describing the error is sent to the browser. This tutorial contains some of the most common error checking methods in Python. Below are some solution about “binary search tree in python” Code Answer’s.
xxxxxxxxxx
1
#Complete Binary Search Tree Using Python 3
2
3
class node:
4
def __init__(self,data):
5
self.data=data
6
self.left=None
7
self.right=None
8
9
class binarytree:
10
def __init__(self):
11
self.root=None
12
13
#INSERT
14
15
def insert(self,data):
16
if self.root==None:
17
self.root=node(data)
18
else:
19
self._insert(data,self.root)
20
def _insert(self,data,cur_node):
21
if data<cur_node.data:
22
if cur_node.left==None:
23
cur_node.left=node(data)
24
else:
25
self._insert(data,cur_node.left)
26
elif data>cur_node.data:
27
if cur_node.right==None:
28
cur_node.right=node(data)
29
else:
30
self._insert(data,cur_node.right)
31
else:
32
print('Data In Treee Already')
33
34
#REMOVE
35
36
def remove(self,data):
37
if self.root!=None:
38
self._remove(data,self.root)
39
def _remove(self,data,cur_node):
40
if cur_node == None:
41
return cur_node
42
if data<cur_node.data:
43
cur_node.left=self._remove(data,cur_node.left)
44
elif data>cur_node.data:
45
cur_node.right=self._remove(data,cur_node.right)
46
else:
47
if cur_node.left is None and cur_node.right is None:
48
print('Removing Leaf Node')
49
if cur_node==self.root:
50
self.root=None
51
del cur_node
52
return None
53
if cur_node.left is None:
54
print('Removing None with Right Child')
55
if cur_node==self.root:
56
self.root=cur_node.right
57
tempnode=cur_node.right
58
del cur_node
59
return tempnode
60
elif cur_node.right is None:
61
print('Removing None with Left Child')
62
if cur_node==self.root:
63
self.root=cur_node.left
64
tempnode=cur_node.left
65
del cur_node