-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathc6_1029_tree.py
99 lines (88 loc) · 2.13 KB
/
c6_1029_tree.py
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# # 1.列表法
# def binary_tree(root):
# tree = [root, [], []]
# # print(tree, len(tree), len(tree[1]))
# # t = tree.pop(1)
# # print(t, len(t), tree)
# return tree
#
#
# def insert_left_child(root, left_child):
# t = root.pop(1)
# if len(t) > 1: # 左子树至少有三个元素,这里可以是0,1,2
# root.insert(1, [left_child, t, []])
# else:
# root.insert(1, [left_child, [], []])
# return root
#
#
# def insert_right_child(root, right_child):
# t = root.pop(2)
# if len(t) > 1: # 左子树至少有三个元素,这里可以是0,1,2
# root.insert(2, [right_child, [], t])
# else:
# root.insert(2, [right_child, [], []])
# return root
#
#
# def get_root_val(root):
# return root[0]
#
#
# def set_root_val(root, new):
# root[0] = new
#
#
# def get_left_child(root):
# return root[1]
#
#
# def get_right_child(root):
# print(root[2])
# return root[2]
#
#
# binary_tree('animal')
#
# r = binary_tree(3)
# insert_right_child(r, 90)
# insert_right_child(r, 'next')
# set_root_val(r, 'head')
# get_right_child(r)
# print(r)
# 节点法:
class Tree2():
def __init__(self, root):
self.data = root
self.left = None
self.right = None
def insert_left(self, newleft):
if self.left is None:
self.left = Tree2(newleft)
else:
t = Tree2(newleft)
t.left = self.left
self.left = t
def insert_right(self, newright):
if self.right is None:
self.right = Tree2(newright)
else:
t = Tree2(newright)
t.right = self.right
self.right = t
def get_root(self):
return self.data
def set_root(self, newroot):
self.data = newroot
def get_right(self):
return self.right
# return self.right.data 只能返回当前最新的data
r = Tree2(3)
r.insert_right(90)
r.insert_right('next')
r.set_root('head')
print(r.get_right())
print(r.get_root())
# print()
# print()
print(r)