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
52
53
54
|
# 1. Use list of lists to implement Tree
def make_binary_tree(root):
return [root, [], []]
# 插入左节点
def insert_left(root, new_child):
old_child = root.pop(1)
# 假如左边本来就有 subtree,我就替换掉它的位置,让它成为我的左 subtree
if len(old_child) > 1:
root.insert(1, [new_child, old_child, []])
# 假如左边的长度 = 1(也就是空的),那我就直接用一个长度 = 3 的 sublist 代替它
else:
root.insert(1, [new_child, [], []])
return root
# 插入右节点
def insert_right(root, new_child):
old_child = root.pop(2)
if len(old_child) > 1:
root.insert(2, [new_child, [], old_child])
else:
root.insert(2, [new_child, [], []])
return root
def get_root_val(root):
return root[0]
def set_root_val(root, new_value):
root[0] = new_value
def get_left_child(root):
return root[1]
def get_right_child(root):
return root[2]
a_tree = make_binary_tree(3)
insert_left(a_tree, 4)
insert_left(a_tree, 5)
insert_right(a_tree, 6)
insert_right(a_tree, 7)
left_child = get_left_child(a_tree)
print(left_child)
set_root_val(left_child, 9)
print(a_tree)
insert_left(left_child, 11)
print(a_tree)
print(get_right_child(get_right_child(a_tree)))
|