用列表构造和访问树
def binaryTree(root):
"""
构建一个简单的列表
有一个根节点和两个作为子节点的空列表
"""
return [root, [], []]
def insertLeftTree(root, newBranch):
"""
插入左子树
先获取当前的左子树所对应的列表,再加入新的左子树
将旧的左子树作为新的节点的左子树
"""
t = root.pop(1)
if len(t) > 1:
root.insert(1, [newBranch, t, []])
else:
root.insert(1, [newBranch, [], []])
return root
def insertRightTree(root, newBranch):
"""
插入左子树
先获取当前的左子树所对应的列表,再加入新的左子树
将旧的左子树作为新的节点的左子树
"""
t = root.pop(2)
if len(t) > 1:
root.insert(2, [newBranch, [], t])
else:
root.insert(2, [newBranch, [], []])
return root
def getRootVal(root):
"""
访问节点
"""
return root[0]
def setRootVal(root, newVal):
"""
修改节点的值
"""
root[0] = newVal
def getLeftChild(root):
"""
访问左子树
"""
return root[1]
def getRightChild(root):
"""
访问右子树
"""
return root[2]