Skip to content

Commit dc528b3

Browse files
committed
tree class representation
1 parent 9e5c553 commit dc528b3

File tree

3 files changed

+69
-1
lines changed

3 files changed

+69
-1
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ but it also contains other data structures, algorithms and problems.
7474

7575
### [Trees]()
7676
- [List of lists representation]()
77+
- [Class representation]()
7778

7879
### [Sorting](https://github.com/ivanmmarkovic/Problem-Solving-with-Algorithms-and-Data-Structures-using-Python/tree/master/sorting)
7980
- [Bubble sort](https://github.com/ivanmmarkovic/Problem-Solving-with-Algorithms-and-Data-Structures-using-Python/blob/master/sorting/bubble-sort.py)

Diff for: trees/class-representation.py

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
class TreeNode:
2+
def __init__(self, key=None, left=None, right=None):
3+
self.key = key
4+
self.left = left
5+
self.right = right
6+
7+
def insert_root_value(self, key=None):
8+
self.key = key
9+
10+
def insert_left(self, key=None):
11+
self.left = TreeNode(key, self.left)
12+
13+
def insert_right(self, key=None):
14+
self.right = TreeNode(key, None, self.right)
15+
16+
def get_root_value(self):
17+
return self.key
18+
19+
def get_left_child(self):
20+
return self.left
21+
22+
def get_right_child(self):
23+
return self.right
24+
25+
26+
# Write a function build_tree that returns a tree
27+
# using the list of lists functions that look like this :
28+
# a
29+
# / \
30+
# b c
31+
# \ / \
32+
# d e f
33+
34+
35+
def build_tree() -> TreeNode:
36+
tree: TreeNode = TreeNode('a')
37+
tree.insert_right('f')
38+
tree.insert_right('c')
39+
tree.get_right_child().insert_left('e')
40+
41+
tree.insert_left('b')
42+
tree.get_left_child().insert_right('d')
43+
44+
return tree
45+
46+
47+
binary_tree: TreeNode = build_tree()
48+
49+
50+
def print_tree(tree: TreeNode):
51+
if tree is not None:
52+
print_tree(tree.get_left_child())
53+
print(tree.key, end=", ")
54+
print_tree(tree.get_right_child())
55+
56+
57+
print_tree(binary_tree)
58+
59+
# ['a',
60+
# ['b',
61+
# [],
62+
# ['d', [], []]],
63+
# ['c',
64+
# ['e', [], []],
65+
# ['f', [], []]
66+
# ]
67+
# ]

Diff for: trees/list-representation.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def build_tree() -> list:
5656
print(binary_tree)
5757

5858

59-
# ['a',
59+
# ['a',
6060
# ['b',
6161
# [],
6262
# ['d', [], []]],

0 commit comments

Comments
 (0)