Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python binary tree

class Binarytree:
    def __init__(self, node):
        """

       :param node: root node
       """
        self.node = node
        self.left = None
        self.right = None

    def add_node(self, node):
        """

       :param node: append node
       :return: None
       """
        if node == self.node:
            return

        if node < self.node:
            if self.left:
                self.left.add_node(node)
            else:
                self.left = Binarytree(node)
        else:
            if self.right:
                self.right.add_node(node)
            else:
                self.right = Binarytree(node)

    def search(self, val):
        """

       :param val: value to search in binary tree
       :return: True if found else False
       """
        if val == self.node:
            return True
        if val < self.node:
            if self.left:
                return self.left.search(val)
            else:
                return False
        else:
            if self.right:
                return self.right.search(val)
            else:
                return False

    def print_nodes(self):
        """
        print all node values to console window
       :return: None
       """

        if self.left:
            self.left.print_nodes()

        print(self.node)

        if self.right:
            self.right.print_nodes()

        return False


def build_tree(node):
    """

   :param node: list of nodes
   :return: Binarytree with nodes
   """
    root = Binarytree(node[0])
    for i in range(1, len(node)):
        root.add_node(node[i])
    return root


if __name__ == '__main__':
    nodes = [30, 10, 40, 22, 15, 18]
    tree = build_tree(nodes)
    tree.add_node(18)
    tree.add_node(20)
    print("15 found in binary tree", tree.search(15))
    print("100 found in binary tree", tree.search(100))
    tree.print_nodes()
Source by codefreelance.net #
 
PREVIOUS NEXT
Tagged: #python #binary #tree
ADD COMMENT
Topic
Name
9+7 =