Dimitris Kougioumtzis Blog About technology

Binary search tree

Category Python

Posted on April 7, 2018



Binary search tree


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
class Node:
    def __init__(self, data=None, right=None, left=None):
        self.data = data
        self.right = right
        self.left = left

    def __str__(self):
        return str(self.data)

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

    def contains(self, value):
        if value == self.data:
            return True
        else:
            if value < self.data:
                if self.left is None:
                    return False
                else:
                    return self.left.contains(value)
            else:
                if self.right is None:
                    return False
                else:
                    return self.right.contains(value)

    def in_order(self):
        if self.left:
            self.left.in_order()
        print(self.data)
        if self.right:
            self.right.in_order()

    def pre_order(self):
        print(self.data)
        if self.left:
            self.left.pre_order()
        if self.right:
            self.right.pre_order()

    def post_order(self):
        if self.left:
            self.left.post_order()
        if self.right:
            self.right.post_order()
        print(self.data)



if __name__ == '__main__':
    a = Node()
    a.data = 10
    a.insert_data(15)
    a.insert_data(5)
    a.insert_data(8)
    a.in_order()
    print('\n')
    a.pre_order()
    print('\n')
    a.post_order()
    print(a.contains(8))

About

My name is Dimitris Kougioumtzis and i work as a Web developer at Rapidbounce Company

Elsewhere