Answers for "python binarytree"

5

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)
    
    def inorder(self):
        element = [ ]
        
        if self.left:
            element += self.left.inorder()
        
        element.append(self.data)
        
        if self.right:
            element += self.right.inorder()
        
        return element
    
    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.inorder())
    print(tree.search(38))
Posted by: Guest on August-03-2021
1

Binary Tree Python

class BinaryTree:

    def __init__(self, value):

        self.left = None
        self.right = None
        self.value = value

    def insert(self, value):

        if self.value:
            if data < self.value:
                if self.left is None:
                    self.left = BinaryTree(value)
                else:
                    self.left.insert(value)
            elif data > self.value:
                if self.right is None:
                    self.right = BinaryTree(value)
                else:
                    self.right.insert(value)
        else:
            self.value = value

    def PrintTree(self):
        if self.left:
            self.left.PrintTree()
        print( self.data),
        if self.right:
            self.right.PrintTree()

root = BinaryTree(100)
root.insert(50)
root.insert(55)
root.insert(60)
root.insert(20)
root.insert(52)


root.PrintTree()
PythonCopy
Posted by: Guest on September-06-2021

Python Answers by Framework

Browse Popular Code Answers by Language