aboutsummaryrefslogtreecommitdiff
path: root/challenge-057/lubos-kolouch/python/ch-1.py
blob: e7dd3485dbcc74c9d1a6e7d69b8b449af0003c31 (plain)
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-

class BinaryTree:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

    def invert(self):
        self.left, self.right = self.right, self.left
        if self.left:
            self.left.invert()
        if self.right:
            self.right.invert()

    def pretty_print(self, padding="", branch_padding=""):
        if self.right:
            self.right.pretty_print(padding + " ", padding + "|")

        print(branch_padding, end="")
        if branch_padding:
            print("--", end="")
        print(self.value)

        if self.left:
            self.left.pretty_print(padding + " ", padding + "|")


if __name__ == "__main__":
    tree = BinaryTree(
        1,
        BinaryTree(
            2,
            BinaryTree(4),
            BinaryTree(5)
        ),
        BinaryTree(
            3,
            BinaryTree(6),
            BinaryTree(7)
        )
    )

    print("Original tree:")
    tree.pretty_print()

    tree.invert()

    print("\nInverted tree:")
    tree.pretty_print()