Answers for "python function to search value in a binary search tree"

10

search element in binary tree python

class Binarytree:
    def __init__(self,data):
        self.data = data
        self.left = None
        self.right = None
    
    def addChild(self, data):
        if data == self.data:
            return
        
        if data < self.data:
            if self.left:
                self.left.addChild(data)
            else:
                self.left = Binarytree(data)
        else:
            if self.right:
                self.right.addChild(data)
            else:
                self.right = Binarytree(data)
    
    # This functions find element in binary tree
    def search(self,val):
        if val == self.data:
            return True
        if val < self.data:
            if self.left:
                return self.left.search(val)
            else:
                return False
        else:
            if self.right:
                return self.right.search(val)
            else:
                return False

def buildtree(element):
    root = Binarytree(element[0])
    for i in range(1,len(element)):
        root.addChild(element[i])
    return root
    
if __name__ == '__main__':
    element = [39, 87, 21, 42, 95, 52, 12]
    tree = buildtree(element)
    print(tree.search(38))
Posted by: Guest on August-03-2021

Code answers related to "python function to search value in a binary search tree"

Python Answers by Framework

Browse Popular Code Answers by Language