Python list实现简单二叉树
BinaryTree创建仅有根节点的二叉树
insertLeft/insertRight将新节点插入树中作为其直接的左/右子节点
get/setRootVal取得或设置根节点getLeft/RightChild返回左/右子树
def BinaryTree(r):
return [r,[],[]]
def insertLeft(root,newBranch):
t=root.pop(1)
if len(t)>1:
root.insert(1,[newBranch,t,[]])
else:
root.insert(1,[newBranch,[],[]])
return root
def insertRight(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,val):
root[0]=val
def getLeftChild(root):
return root[1]
def getRightChild(root):
return root[2]
r=BinaryTree(2)
insertLeft(r,3)
insertLeft(r,4)
insertRight(getLeftChild(r),5)
insertRight(r,7)
print(r)
>>>[2, [4, [3, [], []], [5, [], []]], [7, [], []]]