In: Computer Science
Creat a python method for a binary tree class that has an inputted lookup value and will output if the lookup values exist within the Binary Tree by returning True or False. Exists within the binary tree -True. No exist within the binary tree - false.Test the method in your code
Following is the code snippet to Search a node in Binary Tree. In following code ifNodeExists is the required method, see comments for explanation. I have also added screen shot of my code execution.
# Function to create a new tree node
class newNode:
# Constructor for newNode
def __init__(node, nodeValue):
node.nodeValue = nodeValue
node.left = None
node.right = None
# Function to check if the given node exists in it
# input parameter node is root node of binary tree
# input paramenter key means value to look for.
def ifNodeExists(node, key):
if (node == None):
return False
if (node.nodeValue == key):
return True
# then recursively call ifNodeExists on left tree
res1 = ifNodeExists(node.left, key)
# node found
if res1:
return True
# Node not found in left node so now
# recursively call ifNodeExists on right tree
res2 = ifNodeExists(node.right, key)
return res2
# Main code
if __name__ == '__main__':
root = newNode(0)
root.left = newNode(10)
root.left.left = newNode(30)
root.left.left.left = newNode(70)
root.left.right = newNode(40)
root.left.right.left = newNode(80)
root.left.right.right = newNode(90)
root.right = newNode(20)
root.right.left = newNode(50)
root.right.right = newNode(60)
# value to look for
key = 20
# adding messages as given in question
if (ifNodeExists(root, key)):
print("Exists within the binary tree - True.")
else:
print("No exist within the binary tree - False.")