数据结构:树的嵌套列表实现

数据结构:树的嵌套列表实现


 

 1 # 生成一个列表
 2 def BinaryTree(r):
 3     return [r, [], []]
 4 
 5 
 6 # 在左边插入节点
 7 def insertLeft(root, newBranch):
 8     t = root.pop(1)
 9     if len(t) > 1:
10         root.insert(1, [newBranch, t, []])
11     else:
12         root.insert(1, [newBranch, [], []])
13     return root
14 
15 
16 # 在右边插入节点
17 def insertRight(root, newBranch):
18     t = root.pop(2)
19 
20     if len(t) > 1:
21         root.insert(2, [newBranch, [], t])
22     else:
23         root.insert(2, [newBranch, [], []])
24     return root
25 
26 
27 # 获取根节点
28 def getRootVal(root):
29     return root[0]
30 
31 
32 # 设置根节点
33 def setRootVal(root, newVal):
34     root[0] = newVal
35 
36 
37 # 获取左孩子节点
38 def getLeftChild(root):
39     return root[1]
40 
41 
42 # 获取右孩子节点
43 def getRightChild(root):
44     return root[2]
45 
46 
47 r = BinaryTree(3)
48 insertLeft(r, 4)
49 insertLeft(r, 5)
50 insertRight(r, 6)
51 insertRight(r, 7)
52 l = getLeftChild(r)
53 print(l)
54 
55 setRootVal(l, 9)
56 print(r)
57 insertLeft(l, 11)
58 print(r)
59 print(getRightChild(getRightChild(r)))

 

posted @ 2021-12-04 13:35  无限赫兹  阅读(104)  评论(0)    收藏  举报