I tried to implement the binary tree program in python. I want to add one more function to get the level of a specific node.
eg:-
10 # level 0
/ \
5 15 # level 1
/ \
3 7 # level 2
if we search the level of node 3, it should return
class BinaryTree:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
if self.data == data:
return
if self.data<data:
if self.left:
self.left.insert(data)
else:
self.left = BinaryTree(data)
else:
if self.right:
self.right.insert(data)
else:
self.right = BinaryTree(data)
def print_tree(self):
if self:
print(self.data)
if self.left:
self.left.print_tree()
elif self.right:
self.right.print_tree()
def get_level(self, data, level=0):
print(type(data))
level += 1
if self.data == data:
return level
elif self.left and self.right:
if self.left:
self.left.get_level(data)
elif self.right:
self.right.get_level(data)
return level
def in_order(self):
if self:
#left
in_order(self.left)
#root
print(self.data, '->')
#right
in_order(self.right)
This is my code for Binary tree. I need to add another function to this class which will tell the level of a node after giving the value
For example:
def get_level(node):
#some code
return level
get_level(10) # returns the level of the node 10
source https://stackoverflow.com/questions/72688811/how-to-get-the-level-of-a-node-in-binary-tree-using-python
Comments
Post a Comment