代码改变世界

Algorithm - Binary search

2021-06-23 16:49  WayneWei  阅读(32)  评论(0编辑  收藏  举报

Algorithm implementation Binary search:

# Binary tree

class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

    def insert(self, data):
        if data < self.data:
            if self.left is None:
                self.left = Node(data)
            else:
                self.left.insert(data)

        if data > self.data:
            if self.right is None:
                self.right = Node(data)
            else:
                self.right.insert(data)

    def find(self, data):
        founded = '%s is founded in binary tree' % data
        if data < self.data:
            if self.left is None:
                founded = '%s is not found' % data
            else:
                founded = self.left.find(data)
        elif data > self.data:
            if self.right is None:
                founded = '%s is not found' % data
            else:
                founded = self.right.find(data)

        return founded

root = Node(7)
root.insert(6)
root.insert(9)
print(root.find(2))
print(root.find(6))

Testing output:

D:\test\venv\Scripts\python.exe D:/test/algorithm.py
2 is not found
6 founded in binary tree

Process finished with exit code 0