Skip to content

Commit 44fbb44

Browse files
committed
added tree datastructure and invert_tree algorithm
1 parent 7a04d57 commit 44fbb44

File tree

3 files changed

+74
-67
lines changed

3 files changed

+74
-67
lines changed

c/sortingAlgorithms/bubble_sort.c

Lines changed: 0 additions & 26 deletions
This file was deleted.

c/sortingAlgorithms/quicksort.c

Lines changed: 0 additions & 41 deletions
This file was deleted.

python/datastructures/tree.py

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
from __future__ import annotations
2+
3+
4+
class Tree:
5+
def __init__(self, val: int, left: Tree=None, right: Tree=None) -> None:
6+
self.val = val
7+
self.left = left
8+
self.right = right
9+
10+
def __str__(self) -> str:
11+
curr = self
12+
result = [curr.val]
13+
stack = []
14+
15+
if self.left and self.right:
16+
stack = [curr.left, curr.right]
17+
18+
while stack:
19+
curr = stack.pop(0)
20+
result.append(curr.val)
21+
22+
if curr.left is not None:
23+
stack.extend([curr.left, curr.right])
24+
25+
return str(result)
26+
27+
def _invert(self, tree: Tree) -> Tree:
28+
if tree is None:
29+
return tree
30+
31+
self._invert(tree.left)
32+
self._invert(tree.right)
33+
34+
tree.left, tree.right = tree.right, tree.left
35+
36+
return tree
37+
38+
def invert(self) -> Tree:
39+
self = self._invert(self)
40+
41+
return self
42+
43+
44+
45+
46+
47+
if __name__ == "__main__":
48+
# tests
49+
50+
tree = Tree(4, Tree(2, Tree(1), Tree(3)), Tree(7, Tree(6), Tree(9)))
51+
# 4
52+
# / \
53+
# 2 7
54+
# / \ /\
55+
# 1 3 6 9
56+
57+
print(tree)
58+
tree.invert()
59+
print(tree)
60+
tree2 = Tree(1, Tree(2, tree, tree), Tree(3, tree, tree))
61+
# 1
62+
# / \
63+
# 2 3
64+
# /\ /\
65+
# 4 .. .. ..
66+
# / \
67+
# 2 7
68+
# / \ / \
69+
# 1 3 6 9
70+
71+
72+
print(tree2)
73+
tree2.invert()
74+
print(tree2)

0 commit comments

Comments
 (0)