Skip to content

Commit 0a76d92

Browse files
committed
add Tree data structure :tree:
1 parent 44b2b9c commit 0a76d92

File tree

6 files changed

+44
-0
lines changed

6 files changed

+44
-0
lines changed

Diff for: DataStructure/Linear/__init__.py

Whitespace-only changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

Diff for: DataStructure/Tree/__init__.py

Whitespace-only changes.

Diff for: DataStructure/Tree/tree.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Tree(object):
2+
height = None
3+
weight = None
4+
root = None
5+
6+
def __init__(self, key, children):
7+
self.children = children
8+
self.key = key
9+
if self.root is None:
10+
self.root = self
11+
12+
def depth(self):
13+
if self.root is None:
14+
return 0
15+
16+
def depth_func(node):
17+
if len(node.children) == 0:
18+
return 1
19+
depth_child = []
20+
for child in node.children:
21+
depth_child.append(depth_func(child) + 1)
22+
return max(depth_child)
23+
24+
return depth_func(self.root)
25+
26+
def print_tree(self):
27+
if self.root is None:
28+
print('tree is None')
29+
return
30+
31+
def print_func(node, depth):
32+
if depth == 0:
33+
print(' ' * depth + str(node.key))
34+
else:
35+
print(' ' + ' ' * (depth - 1) + '--' + str(node.key))
36+
for child in node.children:
37+
print_func(child, depth + 1)
38+
39+
print_func(self.root, 0)
40+
41+
42+
root = Tree(1, [Tree(2, [Tree(3, [])]), Tree(4, [])])
43+
print(root.depth())
44+
root.print_tree()

0 commit comments

Comments
 (0)