Python构建二叉树

构建的树状图
tree

伪代码

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, newVal):
	root[0] = newVal
def getLeftChild(root):
	return root[1]
def getRightChild(root):
	return root[2]

tree = BinaryTree('a')
insertLeft(tree, 'b')
insertRight(tree, 'c')
insertLeft((getLeftChild(tree)), 'd')
insertRight((getLeftChild(tree)), 'e')
insertLeft((getRightChild(tree)), 'f')
print(tree)

程序输出

['a', ['b', ['d', [], []], ['e', [], []]], ['c', ['f', [], []], []]]
发布了92 篇原创文章 · 获赞 15 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/zZzZzZ__/article/details/103951269