1. 二叉树实现
myTree = ['a', #root
['b', #left subtree
['d',[],[]],
['e',[],[]]
],
['c',# right subtree
['f',[],[]],
[]
]
]
print("root",myTree[0])
print("left subtree",myTree[1])
print("right subtree",myTree[2])
C:\Users\Amber\PycharmProjects\untitled5\venv\Scripts\python.exe C:/Training/AI/Python/二叉树.py
root a
left subtree ['b', ['d', [], []], ['e', [], []]]
right subtree ['c', ['f', [], []], []]
def BinaryTree(r):
return [r,[],[]] # 返回根节点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(1, [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)
C:\Users\Amber\PycharmProjects\untitled5\venv\Scripts\python.exe C:/Training/AI/Python/二叉树02.py
['a', ['c', ['e', [], []], ['d', [], []]], ['b', ['f', [], []], []]]
2. 二叉树遍历
# 先序遍历, 遍历顺序是从根节点开始,子节点顺序是从左向右,垂直深度优先,水平顺序次优
def preorder(tree):
if tree != []:
print(tree[0],end='') #对根的访问
preorder(tree[1]) #对左子树的访问
preorder(tree[2]) #对右子树的访问
tree=['a', #根节点
['b', #左子树
['d',[],[]],
['e',[],[]]],
['c', #Right subtree
['f',[],[]],
[]]
]
preorder(tree)
C:\Users\Amber\PycharmProjects\untitled5\venv\Scripts\python.exe C:/Training/AI/Python/二叉树03.py
abdecf
# 中序遍历, 遍历顺序是从左边深度最长的子节点开始,逐步从左到右遍历
def inorder(tree):
if tree != []:
inorder(tree[1]) #对左子树的访问
print(tree[0],end='') #对根的访问
inorder(tree[2]) #对右子树的访问
tree=['a', #根节点
['b', #左子树
['d',[],[]],
['e',[],[]]],
['c', #Right subtree
['f',[],[]],
[]]
]
inorder(tree)
C:\Users\Amber\PycharmProjects\untitled5\venv\Scripts\python.exe C:/Training/AI/Python/二叉树04.py
dbeafc
# 后序遍历, 遍历顺序是从左边深度最长的子节点开始,逐步从下到上遍历
def postorder(tree):
if tree != []:
postorder(tree[1]) #对左子树的访问
postorder(tree[2]) #对右子树的访问
print(tree[0],end='') #对根的访问
tree=['a', #根节点
['b', #左子树
['d',[],[]],
['e',[],[]]],
['c', #Right subtree
['f',[],[]],
[]]
]
postorder(tree)
C:\Users\Amber\PycharmProjects\untitled5\venv\Scripts\python.exe C:/Training/AI/Python/二叉树05.py
debfca
# 计算二叉树节点个数
# 当树为空时,节点个数为0
# 否则,节点总数为根节点个数+左节点个数+右节点个数
def count(root):
if root == []:
return 0
else:
n1=count(root[1])
n2=count(root[2])
n = 1 + n1 + n2
return n
tree=['a', #根节点
['b', #左子树
['d',[],[]],
['e',[],[]]],
['c', #Right subtree
['f',[],[]],
[]]
]
sum = count(tree)
print(sum)
C:\Users\Amber\PycharmProjects\untitled5\venv\Scripts\python.exe C:/Training/AI/Python/二叉树06.py
6
3. 二叉树排序