二叉树列表版
def BinaryTree():
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
'''
插入左子节点函数,根据列表结构,根是0,1是左子树,2是右子树
左子树默认是[1,[2,[],[]]],[3,[],[]]],以上为例,2是左子树,左子树又带两个空列表的左儿子和右儿子节点,所以如果是这样的结构root.pop(1),len(t)==3
In [16]: t = [1,[2,[],[]],[3]]
In [17]: x = t.pop(1)
In [18]: print x
[2, [], []]
In [19]: len(x)
Out[19]: 3
当左子树不为空时,应该是把左子树pop出给t,t左子树接到新插入左子树下方。
'''
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,newVal):
root[0] = newVal
def getLeftChild(root):
return root[1]
def getRightChild(root):
return root[2]