Intro to Python 3. Implimenting BST (Binary Search Tree). In this program, we tr
ID: 3912659 • Letter: I
Question
Intro to Python 3. Implimenting BST (Binary Search Tree). In this program, we try to implement a BST and there are tests on the bottom that we using to test the code. And I am stuck with add, Inorder, postorder, preorder, BFS. I kept getting errors when i run the program or try to test it. Can somebody please help me out with this project, thak you so much.
https://docs.google.com/document/d/18uFn92dCLgHEvSwRIiemkxxr0fzx5KPA5renEVB_TUo/edit?usp=sharing << Project outline/instruction
https://docs.google.com/document/d/1uJAjGs79ePe6iZkiUgsu5Mx4CukGrS7AK4Vl20ckIeI/edit?usp=sharing << My code/attempt
Explanation / Answer
//Preorder Traversal using Recursion
def preorder(root):
if root:
print(root.val)
preorder(root.left)
preorder(root.right)
//Inorder traversal using Recursion
def inorder(root):
if root:
inorder(root.left)
print(root.val)
inorder(root.right)
//Postorder traversal using Recursion
def postorder(root):
if root:
postorder(root.left)
postorder(root.right)
print(root.val)
//BFS(Breadth First Seach) in BST
//fuction to print BFS by printing node level by level
def printBFS(root):
h = height(root)
for i in range(1, h+1):
printCurrentLevel(root, i)
//function to print the nodes at level(as given in parameter of function)
def printCurrentLevel(root , level):
if root is None:
return
if level == 1:
print "%d" %(root.val),
elif level > 1 :
printCurrentLevel(root.left , level-1)
printCurrentLevel(root.right , level-1)
//function to determine no of levels tree have
def height(node):
if node is None:
return 0
else :
lheight = height(node.left) //height of Left subtree
rheight = height(node.right) //height of Right subtree
if lheight > rheight :
return lheight+1
else:
return rheight+1
//Adding a node in BST
def add(self, value):
with this fuction, first create a new node for BST tree with node_value=value
and then call addnode_(root,node) to add new node in BST
def add_node(root,node):
if root is None:
root = node
else:
if root.val < node.val:
if root.right is None:
root.right = node
else:
add_node(root.right, node)
else:
if root.left is None:
root.left = node
else:
add_node(root.left, node)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.