Skip to content

Commit c70ca6d

Browse files
committed
add tree size function and fix print NoType Error
1 parent 0a76d92 commit c70ca6d

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

Diff for: DataStructure/Tree/tree.py

+22-3
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ def print_tree(self):
2929
return
3030

3131
def print_func(node, depth):
32+
if node is None:
33+
return
3234
if depth == 0:
3335
print(' ' * depth + str(node.key))
3436
else:
@@ -38,7 +40,24 @@ def print_func(node, depth):
3840

3941
print_func(self.root, 0)
4042

43+
def size(self):
44+
def inner_size(node):
45+
"""
46+
子树的大小
47+
:param node:
48+
:return:
49+
"""
50+
size_num = 0
51+
if node is None:
52+
return size_num
53+
for child in node.children:
54+
size_num += inner_size(child)
55+
return size_num + 1
56+
57+
return inner_size(self)
4158

42-
root = Tree(1, [Tree(2, [Tree(3, [])]), Tree(4, [])])
43-
print(root.depth())
44-
root.print_tree()
59+
if __name__ == '__main__':
60+
root = Tree(1, [Tree(2, [Tree(3, [])]), Tree(4, [])])
61+
print(root.depth())
62+
root.print_tree()
63+
print(root.children[0].size())

0 commit comments

Comments
 (0)