I am Trying to solve the following question Monk and Cursed Tree
In this Question i am given a list of values which are inserted into the Binary Search Tree and then other 2 values are given.The starting node and the ending node.Between these values,i need to find the maximum value(including the starting node and Ending Node)
Example-4,7,8,6,3
Start Node-3
Ending Node-7
The Binary Search Tree for the given list of values
So the path is 3->4->7 and the maximum value in this is 7.
What i have tried is create a function lookup which finds the data in the tree and returns it's parent.What i need to do is call the value returned by my Lookup function again and again and appending the value of parent to another list.Simultaneously call Lookup from end node and append it's parent to the same list.This Operation needs to be carried till the same value is being appended to the list.Once this happens,we know that they have the common ancestor and the path is complete.
Here's what i have tried so far
class Node:
def __init__(self,data):
self.data=data
self.left=None
self.right=None
def Insert_BTreeNode(self,data):
if self.data:
if data<self.data:
if self.left is None:
self.left=Node(data)
else:
self.left.Insert_BTreeNode(data)
elif data>self.data:
if self.right is None:
self.right=Node(data)
else:
self.right.Insert_BTreeNode(data)
else:
self.data=data
def Lookup(self,data,parent=None):
if data<self.data:
if self.left is None:
return None,None
return self.left.Lookup(data,self)
elif data>self.data:
if self.right is None:
return None,None
return self.right.Lookup(data,self)
else:
if (parent is not None):
print(parent.data)
return (parent)
def next_parent(self,Lookup):
something=Lookup(Lookup)
return something
b_tree=list(map(int,input().split()))
x,y=map(int,input().split())
root=Node(b_tree[0])
b_treepath=[]
for i in range(1,len(b_tree)):
root.Insert_BTreeNode(b_tree[i])
z=root.Lookup(x)
a=root.next_parent(z.data)
Help in solving this question is widely appreciated.