SlideShare a Scribd company logo
1 of 8
Download to read offline
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基礎
anzhong70
 
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
 
Barely Legal Xxx Perl Presentation
Barely Legal Xxx Perl PresentationBarely Legal Xxx Perl Presentation
Barely Legal Xxx Perl Presentation
Attila Balazs
 
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

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
 

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

MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MysoreMuleSoftMeetup
 
Orientation Canvas Course Presentation.pdf
Orientation Canvas Course Presentation.pdfOrientation Canvas Course Presentation.pdf
Orientation Canvas Course Presentation.pdf
Elizabeth Walsh
 

Recently uploaded (20)

Introduction to TechSoup’s Digital Marketing Services and Use Cases
Introduction to TechSoup’s Digital Marketing  Services and Use CasesIntroduction to TechSoup’s Digital Marketing  Services and Use Cases
Introduction to TechSoup’s Digital Marketing Services and Use Cases
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Including Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdfIncluding Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdf
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17
 
PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptx
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Orientation Canvas Course Presentation.pdf
Orientation Canvas Course Presentation.pdfOrientation Canvas Course Presentation.pdf
Orientation Canvas Course Presentation.pdf
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
Ernest Hemingway's For Whom the Bell Tolls
Ernest Hemingway's For Whom the Bell TollsErnest Hemingway's For Whom the Bell Tolls
Ernest Hemingway's For Whom the Bell Tolls
 

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: