SlideShare a Scribd company logo
Complete the implementation of the binary search tree started in class. You know you are done
when the main function runs correctly with all commented lines uncommented, and printing
shows the expected behavior of a BST.
CODE:
# TODO: implement inorder
# TODO: implement find
# TODO: implement maximum, minimum
# TODO: implement successor, predecessor
# TODO: implement delete
def main():
bst = Node(3, None)
for k in [5, 7, 4, 5, 6]:
bst.insert(k)
# print(bst.inorder())
# for k in [4, 3, 6, 2, 1, 7]:
# print("find {}: {}".format(k, bst.find(k) != None))
# for k in [4,3, 2]:
# n = bst.find(k)
# if n != None:
# s = n.successor()
# print("successor of {}: {}".format(k, s.key if s != None else None))
# s = n.predecessor()
# print("predecessor of {}: {}".format(k, s.key if s != None else None))
# s = n.delete()
# print("deleted {}".format(s.key))
# print(bst.inorder())
class Node:
def __init__(self, key, parent):
self.key = key # self is Python for "this"
self.parent = parent
self.left = None
self.right = None
def inorder(self):
'''returns list of the keys in an inorder traversal of the tree rooted at self'''
# TODO: replace "pass" keyword with actual code
# Hint: li.append(value) appends a value to list li
# Hint: li = list1 + list2 returns the concatnenation of list1 and list2
# Hint: use dot notation to call method: inorder(node) ---> node.inorder()
# To test: uncomment line 10 and click "Run"
li = [] # empty list
if self.left is not None:
pass
pass
if self.right is not None:
pass
return li
def insert(self, key):
'''inserts a new node with given key into subtree rooted at self node'''
if key < self.key:
if self.left is None: # None is Python for null, "is" = "==", "is not" = "!="
self.left = Node(key, self)
else:
self.left.insert(key)
else:
if self.right is None:
self.right = Node(key, self)
else:
self.right.insert(key)
def find(self, key):
'''returns a node in the subtree rooted at self with this key or
None if no such key exists'''
# Hint: similar to insert()
# Test: uncomment lines 11 and 12, click "Run"
pass
def minimum(self):
'''returns the node with minimum key in the subtree rooted at self'''
pass
def maximum(self):
'''returns the node with maximum key in the is subtree rooted at self'''
pass
def successor(self):
'''returns successor of the self node or None if it does not have one'''
# TODO: fill the if statement
if self.right is not None:
pass
c, p = self, self.parent
while p is not None and c is p.right:
c, p = p, p.parent
return p
def predecessor(self):
'''returns the predecessor of the self node or None if it does not have one'''
pass
def delete(self):
'''deletes the self node from the tree and returns that node'''
parent, left, right = self.parent, self.left, self.right
# case 0: no children
if left is None and right is None:
if parent is not None:
if self is parent.left:
parent.left = None
else:
parent.right = None
return self
# case 1: one or two children, no parent
elif parent is None:
s = self.predecessor() or self.successor() # whichever is not None
self.key, s.key = s.key, self.key
return s.delete()
# case 2: one child, one parent
# Hint: similar to case 0
elif left == None or right == None:
pass
# case 3: 2 children, one parent
# Hint: similar to case 1
else:
pass
main()
Solution
# TODO: implement inorder
# TODO: implement find
# TODO: implement maximum, minimum
# TODO: implement successor, predecessor
# TODO: implement delete
def main():
bst = Node(3, None)
for k in [5, 7, 4, 5, 6]:
bst.insert(k)
print( bst.inorder())
# print(bst.inorder())
for k in [4, 3, 6, 2, 1, 7]:
print("find {0}: {1}".format(k, bst.find(k) != None))
for k in [4,3, 2]:
n = bst.find(k)
if n != None:
s = n.successor()
print("successor of {}: {}".format(k, s.key if s != None else None))
s = n.predecessor()
print("predecessor of {}: {}".format(k, s.key if s != None else None))
s = n.delete()
print("deleted {}".format(s.key))
print(bst.inorder())
list1=[]
list2=[]
li = []
class Node:
def __init__(self, key, parent):
self.key = key # self is Python for "this"
self.parent = parent
self.left = None
self.right = None
def inorder(self):
#Node.inorder1(self.parent)
'''returns list of the keys in an inorder traversal of the tree rooted at self'''
# TODO: replace "pass" keyword with actual code
# Hint: li.append(value) appends a value to list li
# Hint: li = list1 + list2 returns the concatnenation of list1 and list2
# Hint: use dot notation to call method: inorder(node) ---> node.inorder()
# To test: uncomment line 10 and click "Run"
# empty list
if self.left is not None:
list1.append(self.left.key)
self.left.inorder()
if self.right is not None:
list2.append(self.right.key)
self.right.inorder()
li = list1+list2
return li
def insert(self,key):
'''inserts a new node with given key into subtree rooted at self node'''
if key < self.key:
if self.left is None: # None is Python for null, "is" = "==", "is not" = "!="
self.left = Node(key, self)
else:
self.left.insert(key)
else:
if self.right is None:
self.right = Node(key, self)
else:
self.right.insert(key)
def find(self, key):
#returns a node in the subtree rooted at self with this key or
# None if no such key exists'''
# Hint: similar to insert()
# Test: uncomment lines 11 and 12, click "Run"
if key < self.key:
if self.left is None: # None is Python for null, "is" = "==", "is not" = "!="
return True
else:
return True
elif self.right is None:
return True
else:
return False
def minimum(self):
'''returns the node with minimum key in the subtree rooted at self'''
current = self
# loop down to find the lefmost leaf
while(current.left is not None):
current = current.left
return current.data
def maximum(self):
'''returns the node with maximum key in the is subtree rooted at self'''
current = self
# loop down to find the rightmost right
while(current.right is not None):
current = current.right
return current.data
def successor(self):
'''returns successor of the self node or None if it does not have one'''
# TODO: fill the if statement
if self.right is not None:
return self.right.minimum()
c, p = self, self.parent
while p is not None and c is p.right:
c, p = p, p.parent
return p
def predecessor(self):
'''returns the predecessor of the self node or None if it does not have one'''
pass
def delete(self):
'''deletes the self node from the tree and returns that node'''
parent, left, right = self.parent, self.left, self.right
# case 0: no children
if left is None and right is None:
if parent is not None:
if self is parent.left:
parent.left = None
else:
parent.right = None
return self
# case 1: one or two children, no parent
elif parent is None:
s = self.predecessor() or self.successor() # whichever is not None
self.key, s.key = s.key, self.key
return s.delete()
# case 2: one child, one parent
# Hint: similar to case 0
elif left == None or right == None:
pass
# case 3: 2 children, one parent
# Hint: similar to case 1
else:
pass
main()

More Related Content

Similar to Complete the implementation of the binary search tree started in cla.pdf

第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎
juzihua1102
 
Selfish presentation - ruby internals
Selfish presentation - ruby internalsSelfish presentation - ruby internals
Selfish presentation - ruby internals
Wojciech Widenka
 
SWP - A Generic Language Parser
SWP - A Generic Language ParserSWP - A Generic Language Parser
SWP - A Generic Language Parser
kamaelian
 
Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)
Benjamin Bock
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Cox
lachie
 
Bouncingballs sh
Bouncingballs shBouncingballs sh
Bouncingballs sh
Ben Pope
 
Programs.doc
Programs.docPrograms.doc
Programs.doc
ArnabNath30
 
AI-Programs.pdf
AI-Programs.pdfAI-Programs.pdf
AI-Programs.pdf
ArnabNath30
 
A limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyA limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced Ruby
Vysakh Sreenivasan
 
C programming. Answer question only in C code Ninth Deletion with B.pdf
C programming. Answer question only in C code Ninth Deletion with B.pdfC programming. Answer question only in C code Ninth Deletion with B.pdf
C programming. Answer question only in C code Ninth Deletion with B.pdf
info309708
 
Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.
Workhorse Computing
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
Barely Legal Xxx Perl Presentation
Barely Legal Xxx Perl PresentationBarely Legal Xxx Perl Presentation
Barely Legal Xxx Perl PresentationAttila Balazs
 
360|iDev
360|iDev360|iDev
360|iDev
Aijaz Ansari
 
Elixir in a nutshell - Fundamental Concepts
Elixir in a nutshell - Fundamental ConceptsElixir in a nutshell - Fundamental Concepts
Elixir in a nutshell - Fundamental Concepts
Héla Ben Khalfallah
 
Please help me fix this code! will upvote. The code needs to produce .pdf
Please help me fix this code! will upvote.  The code needs to produce .pdfPlease help me fix this code! will upvote.  The code needs to produce .pdf
Please help me fix this code! will upvote. The code needs to produce .pdf
climatecontrolsv
 
For this homework, you will write a program to create and manipulate.pdf
For this homework, you will write a program to create and manipulate.pdfFor this homework, you will write a program to create and manipulate.pdf
For this homework, you will write a program to create and manipulate.pdf
herminaherman
 

Similar to Complete the implementation of the binary search tree started in cla.pdf (20)

第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎
 
Selfish presentation - ruby internals
Selfish presentation - ruby internalsSelfish presentation - ruby internals
Selfish presentation - ruby internals
 
Mips1
Mips1Mips1
Mips1
 
SWP - A Generic Language Parser
SWP - A Generic Language ParserSWP - A Generic Language Parser
SWP - A Generic Language Parser
 
Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Cox
 
Bouncingballs sh
Bouncingballs shBouncingballs sh
Bouncingballs sh
 
Programs.doc
Programs.docPrograms.doc
Programs.doc
 
AI-Programs.pdf
AI-Programs.pdfAI-Programs.pdf
AI-Programs.pdf
 
A limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyA limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced Ruby
 
C programming. Answer question only in C code Ninth Deletion with B.pdf
C programming. Answer question only in C code Ninth Deletion with B.pdfC programming. Answer question only in C code Ninth Deletion with B.pdf
C programming. Answer question only in C code Ninth Deletion with B.pdf
 
Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
Barely Legal Xxx Perl Presentation
Barely Legal Xxx Perl PresentationBarely Legal Xxx Perl Presentation
Barely Legal Xxx Perl Presentation
 
360|iDev
360|iDev360|iDev
360|iDev
 
Elixir in a nutshell - Fundamental Concepts
Elixir in a nutshell - Fundamental ConceptsElixir in a nutshell - Fundamental Concepts
Elixir in a nutshell - Fundamental Concepts
 
Please help me fix this code! will upvote. The code needs to produce .pdf
Please help me fix this code! will upvote.  The code needs to produce .pdfPlease help me fix this code! will upvote.  The code needs to produce .pdf
Please help me fix this code! will upvote. The code needs to produce .pdf
 
For this homework, you will write a program to create and manipulate.pdf
For this homework, you will write a program to create and manipulate.pdfFor this homework, you will write a program to create and manipulate.pdf
For this homework, you will write a program to create and manipulate.pdf
 

More from sanuoptical

Briefly explain four functions of stems. SolutionFunction of S.pdf
Briefly explain four functions of stems.  SolutionFunction of S.pdfBriefly explain four functions of stems.  SolutionFunction of S.pdf
Briefly explain four functions of stems. SolutionFunction of S.pdf
sanuoptical
 
AVR was one of the first microcontroller families to use A. on-chip .pdf
AVR was one of the first microcontroller families to use  A. on-chip .pdfAVR was one of the first microcontroller families to use  A. on-chip .pdf
AVR was one of the first microcontroller families to use A. on-chip .pdf
sanuoptical
 
A researcher was interested in studying Americans email habits. She .pdf
A researcher was interested in studying Americans email habits. She .pdfA researcher was interested in studying Americans email habits. She .pdf
A researcher was interested in studying Americans email habits. She .pdf
sanuoptical
 
A 50 mL stock sample of cells is diluted 110 six times. If 0.1 mL o.pdf
A 50 mL stock sample of cells is diluted 110 six times. If 0.1 mL o.pdfA 50 mL stock sample of cells is diluted 110 six times. If 0.1 mL o.pdf
A 50 mL stock sample of cells is diluted 110 six times. If 0.1 mL o.pdf
sanuoptical
 
Why are clocks (or timers) discussed in the context of IO systems.pdf
Why are clocks (or timers) discussed in the context of IO systems.pdfWhy are clocks (or timers) discussed in the context of IO systems.pdf
Why are clocks (or timers) discussed in the context of IO systems.pdf
sanuoptical
 
why the SSB receiver re-injects the missing carrier Why add the c.pdf
why the SSB receiver re-injects the missing carrier Why add the c.pdfwhy the SSB receiver re-injects the missing carrier Why add the c.pdf
why the SSB receiver re-injects the missing carrier Why add the c.pdf
sanuoptical
 
80 µl of 10^-5 dilution of E. coli culture was plated on LB agar and.pdf
80 µl of 10^-5 dilution of E. coli culture was plated on LB agar and.pdf80 µl of 10^-5 dilution of E. coli culture was plated on LB agar and.pdf
80 µl of 10^-5 dilution of E. coli culture was plated on LB agar and.pdf
sanuoptical
 
Which of the following statements about pyruvate is most accurate P.pdf
Which of the following statements about pyruvate is most accurate  P.pdfWhich of the following statements about pyruvate is most accurate  P.pdf
Which of the following statements about pyruvate is most accurate P.pdf
sanuoptical
 
Which CLI modes let you use the show running-config commandA. Use.pdf
Which CLI modes let you use the show running-config commandA. Use.pdfWhich CLI modes let you use the show running-config commandA. Use.pdf
Which CLI modes let you use the show running-config commandA. Use.pdf
sanuoptical
 
What is meant by star activity with respect to a restriction enz.pdf
What is meant by star activity with respect to a restriction enz.pdfWhat is meant by star activity with respect to a restriction enz.pdf
What is meant by star activity with respect to a restriction enz.pdf
sanuoptical
 
Type III hypersensitivities are also referred to as immune complex me.pdf
Type III hypersensitivities are also referred to as immune complex me.pdfType III hypersensitivities are also referred to as immune complex me.pdf
Type III hypersensitivities are also referred to as immune complex me.pdf
sanuoptical
 
True, False, Uncertain with Explanation(a) Including an interacti.pdf
True, False, Uncertain with Explanation(a) Including an interacti.pdfTrue, False, Uncertain with Explanation(a) Including an interacti.pdf
True, False, Uncertain with Explanation(a) Including an interacti.pdf
sanuoptical
 
Traits that are detrimental to the long-term survival of an individu.pdf
Traits that are detrimental to the long-term survival of an individu.pdfTraits that are detrimental to the long-term survival of an individu.pdf
Traits that are detrimental to the long-term survival of an individu.pdf
sanuoptical
 
The sampling distribution of the sample mean is the probability dist.pdf
The sampling distribution of the sample mean is the probability dist.pdfThe sampling distribution of the sample mean is the probability dist.pdf
The sampling distribution of the sample mean is the probability dist.pdf
sanuoptical
 
The lantana has which inflorescence morphology type campanulte tub.pdf
The lantana has which inflorescence morphology type  campanulte  tub.pdfThe lantana has which inflorescence morphology type  campanulte  tub.pdf
The lantana has which inflorescence morphology type campanulte tub.pdf
sanuoptical
 
The intensity of the sound of traffic at a busy intersection was mea.pdf
The intensity of the sound of traffic at a busy intersection was mea.pdfThe intensity of the sound of traffic at a busy intersection was mea.pdf
The intensity of the sound of traffic at a busy intersection was mea.pdf
sanuoptical
 
The garden pea is described as self-fertilizing. What does this .pdf
The garden pea is described as self-fertilizing. What does this .pdfThe garden pea is described as self-fertilizing. What does this .pdf
The garden pea is described as self-fertilizing. What does this .pdf
sanuoptical
 
The equation for the time of one swing of a pendulum is given by T = .pdf
The equation for the time of one swing of a pendulum is given by T = .pdfThe equation for the time of one swing of a pendulum is given by T = .pdf
The equation for the time of one swing of a pendulum is given by T = .pdf
sanuoptical
 
The assumption that arrivals follow a Poisson probability distributi.pdf
The assumption that arrivals follow a Poisson probability distributi.pdfThe assumption that arrivals follow a Poisson probability distributi.pdf
The assumption that arrivals follow a Poisson probability distributi.pdf
sanuoptical
 
Some yeasts process xylitol and some cannot. The ability to process .pdf
Some yeasts process xylitol and some cannot. The ability to process .pdfSome yeasts process xylitol and some cannot. The ability to process .pdf
Some yeasts process xylitol and some cannot. The ability to process .pdf
sanuoptical
 

More from sanuoptical (20)

Briefly explain four functions of stems. SolutionFunction of S.pdf
Briefly explain four functions of stems.  SolutionFunction of S.pdfBriefly explain four functions of stems.  SolutionFunction of S.pdf
Briefly explain four functions of stems. SolutionFunction of S.pdf
 
AVR was one of the first microcontroller families to use A. on-chip .pdf
AVR was one of the first microcontroller families to use  A. on-chip .pdfAVR was one of the first microcontroller families to use  A. on-chip .pdf
AVR was one of the first microcontroller families to use A. on-chip .pdf
 
A researcher was interested in studying Americans email habits. She .pdf
A researcher was interested in studying Americans email habits. She .pdfA researcher was interested in studying Americans email habits. She .pdf
A researcher was interested in studying Americans email habits. She .pdf
 
A 50 mL stock sample of cells is diluted 110 six times. If 0.1 mL o.pdf
A 50 mL stock sample of cells is diluted 110 six times. If 0.1 mL o.pdfA 50 mL stock sample of cells is diluted 110 six times. If 0.1 mL o.pdf
A 50 mL stock sample of cells is diluted 110 six times. If 0.1 mL o.pdf
 
Why are clocks (or timers) discussed in the context of IO systems.pdf
Why are clocks (or timers) discussed in the context of IO systems.pdfWhy are clocks (or timers) discussed in the context of IO systems.pdf
Why are clocks (or timers) discussed in the context of IO systems.pdf
 
why the SSB receiver re-injects the missing carrier Why add the c.pdf
why the SSB receiver re-injects the missing carrier Why add the c.pdfwhy the SSB receiver re-injects the missing carrier Why add the c.pdf
why the SSB receiver re-injects the missing carrier Why add the c.pdf
 
80 µl of 10^-5 dilution of E. coli culture was plated on LB agar and.pdf
80 µl of 10^-5 dilution of E. coli culture was plated on LB agar and.pdf80 µl of 10^-5 dilution of E. coli culture was plated on LB agar and.pdf
80 µl of 10^-5 dilution of E. coli culture was plated on LB agar and.pdf
 
Which of the following statements about pyruvate is most accurate P.pdf
Which of the following statements about pyruvate is most accurate  P.pdfWhich of the following statements about pyruvate is most accurate  P.pdf
Which of the following statements about pyruvate is most accurate P.pdf
 
Which CLI modes let you use the show running-config commandA. Use.pdf
Which CLI modes let you use the show running-config commandA. Use.pdfWhich CLI modes let you use the show running-config commandA. Use.pdf
Which CLI modes let you use the show running-config commandA. Use.pdf
 
What is meant by star activity with respect to a restriction enz.pdf
What is meant by star activity with respect to a restriction enz.pdfWhat is meant by star activity with respect to a restriction enz.pdf
What is meant by star activity with respect to a restriction enz.pdf
 
Type III hypersensitivities are also referred to as immune complex me.pdf
Type III hypersensitivities are also referred to as immune complex me.pdfType III hypersensitivities are also referred to as immune complex me.pdf
Type III hypersensitivities are also referred to as immune complex me.pdf
 
True, False, Uncertain with Explanation(a) Including an interacti.pdf
True, False, Uncertain with Explanation(a) Including an interacti.pdfTrue, False, Uncertain with Explanation(a) Including an interacti.pdf
True, False, Uncertain with Explanation(a) Including an interacti.pdf
 
Traits that are detrimental to the long-term survival of an individu.pdf
Traits that are detrimental to the long-term survival of an individu.pdfTraits that are detrimental to the long-term survival of an individu.pdf
Traits that are detrimental to the long-term survival of an individu.pdf
 
The sampling distribution of the sample mean is the probability dist.pdf
The sampling distribution of the sample mean is the probability dist.pdfThe sampling distribution of the sample mean is the probability dist.pdf
The sampling distribution of the sample mean is the probability dist.pdf
 
The lantana has which inflorescence morphology type campanulte tub.pdf
The lantana has which inflorescence morphology type  campanulte  tub.pdfThe lantana has which inflorescence morphology type  campanulte  tub.pdf
The lantana has which inflorescence morphology type campanulte tub.pdf
 
The intensity of the sound of traffic at a busy intersection was mea.pdf
The intensity of the sound of traffic at a busy intersection was mea.pdfThe intensity of the sound of traffic at a busy intersection was mea.pdf
The intensity of the sound of traffic at a busy intersection was mea.pdf
 
The garden pea is described as self-fertilizing. What does this .pdf
The garden pea is described as self-fertilizing. What does this .pdfThe garden pea is described as self-fertilizing. What does this .pdf
The garden pea is described as self-fertilizing. What does this .pdf
 
The equation for the time of one swing of a pendulum is given by T = .pdf
The equation for the time of one swing of a pendulum is given by T = .pdfThe equation for the time of one swing of a pendulum is given by T = .pdf
The equation for the time of one swing of a pendulum is given by T = .pdf
 
The assumption that arrivals follow a Poisson probability distributi.pdf
The assumption that arrivals follow a Poisson probability distributi.pdfThe assumption that arrivals follow a Poisson probability distributi.pdf
The assumption that arrivals follow a Poisson probability distributi.pdf
 
Some yeasts process xylitol and some cannot. The ability to process .pdf
Some yeasts process xylitol and some cannot. The ability to process .pdfSome yeasts process xylitol and some cannot. The ability to process .pdf
Some yeasts process xylitol and some cannot. The ability to process .pdf
 

Recently uploaded

Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
Vivekanand Anglo Vedic Academy
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
Excellence Foundation for South Sudan
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 

Recently uploaded (20)

Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 

Complete the implementation of the binary search tree started in cla.pdf

  • 1. Complete the implementation of the binary search tree started in class. You know you are done when the main function runs correctly with all commented lines uncommented, and printing shows the expected behavior of a BST. CODE: # TODO: implement inorder # TODO: implement find # TODO: implement maximum, minimum # TODO: implement successor, predecessor # TODO: implement delete def main(): bst = Node(3, None) for k in [5, 7, 4, 5, 6]: bst.insert(k) # print(bst.inorder()) # for k in [4, 3, 6, 2, 1, 7]: # print("find {}: {}".format(k, bst.find(k) != None)) # for k in [4,3, 2]: # n = bst.find(k) # if n != None: # s = n.successor() # print("successor of {}: {}".format(k, s.key if s != None else None)) # s = n.predecessor() # print("predecessor of {}: {}".format(k, s.key if s != None else None)) # s = n.delete() # print("deleted {}".format(s.key)) # print(bst.inorder()) class Node: def __init__(self, key, parent): self.key = key # self is Python for "this" self.parent = parent self.left = None self.right = None def inorder(self):
  • 2. '''returns list of the keys in an inorder traversal of the tree rooted at self''' # TODO: replace "pass" keyword with actual code # Hint: li.append(value) appends a value to list li # Hint: li = list1 + list2 returns the concatnenation of list1 and list2 # Hint: use dot notation to call method: inorder(node) ---> node.inorder() # To test: uncomment line 10 and click "Run" li = [] # empty list if self.left is not None: pass pass if self.right is not None: pass return li def insert(self, key): '''inserts a new node with given key into subtree rooted at self node''' if key < self.key: if self.left is None: # None is Python for null, "is" = "==", "is not" = "!=" self.left = Node(key, self) else: self.left.insert(key) else: if self.right is None: self.right = Node(key, self) else: self.right.insert(key) def find(self, key): '''returns a node in the subtree rooted at self with this key or None if no such key exists''' # Hint: similar to insert() # Test: uncomment lines 11 and 12, click "Run" pass def minimum(self): '''returns the node with minimum key in the subtree rooted at self'''
  • 3. pass def maximum(self): '''returns the node with maximum key in the is subtree rooted at self''' pass def successor(self): '''returns successor of the self node or None if it does not have one''' # TODO: fill the if statement if self.right is not None: pass c, p = self, self.parent while p is not None and c is p.right: c, p = p, p.parent return p def predecessor(self): '''returns the predecessor of the self node or None if it does not have one''' pass def delete(self): '''deletes the self node from the tree and returns that node''' parent, left, right = self.parent, self.left, self.right # case 0: no children if left is None and right is None: if parent is not None: if self is parent.left: parent.left = None else: parent.right = None return self # case 1: one or two children, no parent elif parent is None: s = self.predecessor() or self.successor() # whichever is not None self.key, s.key = s.key, self.key return s.delete()
  • 4. # case 2: one child, one parent # Hint: similar to case 0 elif left == None or right == None: pass # case 3: 2 children, one parent # Hint: similar to case 1 else: pass main() Solution # TODO: implement inorder # TODO: implement find # TODO: implement maximum, minimum # TODO: implement successor, predecessor # TODO: implement delete def main(): bst = Node(3, None) for k in [5, 7, 4, 5, 6]: bst.insert(k) print( bst.inorder()) # print(bst.inorder()) for k in [4, 3, 6, 2, 1, 7]: print("find {0}: {1}".format(k, bst.find(k) != None)) for k in [4,3, 2]: n = bst.find(k) if n != None: s = n.successor() print("successor of {}: {}".format(k, s.key if s != None else None)) s = n.predecessor() print("predecessor of {}: {}".format(k, s.key if s != None else None)) s = n.delete() print("deleted {}".format(s.key)) print(bst.inorder())
  • 5. list1=[] list2=[] li = [] class Node: def __init__(self, key, parent): self.key = key # self is Python for "this" self.parent = parent self.left = None self.right = None def inorder(self): #Node.inorder1(self.parent) '''returns list of the keys in an inorder traversal of the tree rooted at self''' # TODO: replace "pass" keyword with actual code # Hint: li.append(value) appends a value to list li # Hint: li = list1 + list2 returns the concatnenation of list1 and list2 # Hint: use dot notation to call method: inorder(node) ---> node.inorder() # To test: uncomment line 10 and click "Run" # empty list if self.left is not None: list1.append(self.left.key) self.left.inorder() if self.right is not None: list2.append(self.right.key) self.right.inorder() li = list1+list2 return li def insert(self,key): '''inserts a new node with given key into subtree rooted at self node''' if key < self.key: if self.left is None: # None is Python for null, "is" = "==", "is not" = "!=" self.left = Node(key, self) else: self.left.insert(key)
  • 6. else: if self.right is None: self.right = Node(key, self) else: self.right.insert(key) def find(self, key): #returns a node in the subtree rooted at self with this key or # None if no such key exists''' # Hint: similar to insert() # Test: uncomment lines 11 and 12, click "Run" if key < self.key: if self.left is None: # None is Python for null, "is" = "==", "is not" = "!=" return True else: return True elif self.right is None: return True else: return False def minimum(self): '''returns the node with minimum key in the subtree rooted at self''' current = self # loop down to find the lefmost leaf while(current.left is not None): current = current.left return current.data def maximum(self): '''returns the node with maximum key in the is subtree rooted at self''' current = self # loop down to find the rightmost right while(current.right is not None): current = current.right return current.data def successor(self):
  • 7. '''returns successor of the self node or None if it does not have one''' # TODO: fill the if statement if self.right is not None: return self.right.minimum() c, p = self, self.parent while p is not None and c is p.right: c, p = p, p.parent return p def predecessor(self): '''returns the predecessor of the self node or None if it does not have one''' pass def delete(self): '''deletes the self node from the tree and returns that node''' parent, left, right = self.parent, self.left, self.right # case 0: no children if left is None and right is None: if parent is not None: if self is parent.left: parent.left = None else: parent.right = None return self # case 1: one or two children, no parent elif parent is None: s = self.predecessor() or self.successor() # whichever is not None self.key, s.key = s.key, self.key return s.delete() # case 2: one child, one parent # Hint: similar to case 0 elif left == None or right == None: pass # case 3: 2 children, one parent # Hint: similar to case 1 else: