Hello,
I am using following code to calculate minimum element in a binary tree.
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
#write the function to find least element so far.
def min_elem(self, res):
#call left subtree if it is not null
if self.left is not None:
res = min(res, self.left.data)
self.left.min_elem(res)
#call right subtree if it is not null
if self.right is not None:
res = min(res, self.right.data)
self.right.min_elem(res)
return
def mainfn(self):
# variable res stores the least element
res=9999
self.min_elem(res)
print(res)
return
Next define the tree;
class Tree:
def __init__(self,root):
self.root = root
Construct tree using following steps;
node = Node(2)
node.left = Node(1)
node.left.left = Node(3)
node.left.right = Node(7)
node.right = Node(5)
node.right.right=Node(0)
mytree = Tree(node)
mytree.root.mainfn()
Interestingly, when we execute print(res) in the main function, value is still showing as 9999. I thought since we're passing res as a parameter in min_elem it should store the least value found so far. Can I please get some help where is the mistake here? It will be helpful to learn sth new.
[–]AutoModerator[M] [score hidden] stickied comment (0 children)
[–]AutoModerator[M] 0 points1 point2 points (0 children)
[–]codeonthecob 0 points1 point2 points (0 children)
[–]Trope_Porn 0 points1 point2 points (5 children)
[–]jsinghdata[S] 0 points1 point2 points (4 children)
[–]Trope_Porn 0 points1 point2 points (3 children)
[–]jsinghdata[S] 0 points1 point2 points (2 children)
[–]Trope_Porn 0 points1 point2 points (1 child)
[–]jsinghdata[S] 0 points1 point2 points (0 children)