python | 算法-二叉树结构及遍历算法
针对b站视频左神算法与数据结构,自己练习对应的python代码
相关链接:
1️⃣b站视频地址
2️⃣视频笔记(其实主要是题目截图)
1. python-二叉树结构
自己动手:
class BTNode():
def __init__(self, key=None, lchild=None, rchild=None):
self.key = key
self.lchild = lchild
self.rchild = rchild
class BiTree():
def __init__(self, data_list):
self.it = iter(data_list) # 迭代器
def createBiTree(self, bt=None):
try:
next_data = next(self.it)
if next_data == "#":
bt = None
else:
bt = BTNode(next_data)
bt.lchild = self.createBiTree(bt.lchild)
bt.rchild = self.createBiTree(bt.rchild)
except Exception as e:
print(e)
return bt
举例说明:
class BTNode():
def __init__(self, key=None, lchild=None, rchild=None):
self.key = key
self.lchild = lchild
self.rchild = rchild
class BiTree():
def __init__(self, data_list):
self.it = iter(data_list) # 迭代器
def createBiTree(self, bt=None):
try:
next_data = next(self.it)
if next_data == "#":
bt = None
else:
bt = BTNode(next_data)
bt.lchild = self.createBiTree(bt.lchild)
bt.rchild = self.createBiTree(bt.rchild)
except Exception as e:
print(e)
return bt
# 先序遍历
def preOrderTrave(self, bt):
if bt is not None:
print(bt.key, end=" ")
self.preOrderTrave(bt.lchild)
self.preOrderTrave(bt.rchild)
# 中序遍历
def inOrderTrave(self, bt):
if bt is not None:
self.inOrderTrave(bt.lchild)
print(bt.key, end=" ")
self.inOrderTrave(bt.rchild)
# 后序遍历
def postOrderTrave(self, bt):
if bt is not None:
self.postOrderTrave(bt.lchild)
self.postOrderTrave(bt.rchild)
print(bt.key, end=" ")
# 输出函数
def printTrave(self, bt):
print("先序遍历:")
self.preOrderTrave(bt)
print('\n')
print("中序遍历:")
self.inOrderTrave(bt)
print('\n')
print("后续遍历:")
self.postOrderTrave(bt)
#测试
data_list = [1, 2, '#', 4, '#', '#', 3, 5, '#', '#', 6, '#', '#']
Btree = BiTree(data_list) # data list -> class Bitree
bt = Btree.createBiTree() # bt -> bi tree root
Btree.printBiTree(bt)
# 终端输出结果
# 先序遍历:
# 1 2 4 3 5 6
#
# 中序遍历:
# 2 4 1 5 3 6
#
# 后续遍历:
# 4 2 5 6 3 1
2. python-二叉树遍历
2.1 python-二叉树遍历 -> 递归
前文的例子已经说明,此处不再赘述。
2.2 python-二叉树遍历 -> 非递归
2.2.1 python-二叉树遍历 -> 非递归 -> 先序遍历
# 此处省略前述数据结构部分
def preOrderTrave(self, bt):
print("pre-order: ")
if bt is not None:
stack = []
stack.append(bt)
while len(stack) != 0:
bt = stack.pop()
print(bt.key, end=" ")
if bt.rchild is not None:
stack.append(bt.rchild)
if bt.lchild is not None:
stack.append(bt.lchild)
else:
print()
# test:
data_list = [1, 2, '#', 4, '#', '#', 3, 5, '#', '#', 6, '#', '#']
biTree = BiTree(data_list) # biTree -> BiTree class, iter
root = biTree.createBiTree() # root -> createBiTree()'s return
biTree.preOrderTrave(root)
# output:
# pre-order:
# 1 2 4 3 5 6
2.2.2 python-二叉树遍历 -> 非递归 -> 中序遍历
def inOrderTrave(self, bt):
print("in-order: ")
if bt is not None:
stack = []
while len(stack) != 0 or bt is not None:
if bt is not None:
stack.append(bt)
bt = bt.lchild
else:
bt = stack.pop()
print(bt.key, end=" ")
bt = bt.rchild
else:
print()
# output:
# in-order:
# 2 4 1 5 3 6
2.2.3 python-二叉树遍历 -> 非递归 -> 后序遍历
def postOrderTrave(self, bt):
print("post-order: ")
if bt is not None:
stack1 = [] # somebody come and go
stack2 = [] # root + right + left
stack1.append(bt)
while len(stack1) != 0:
bt = stack1.pop()
stack2.append(bt)
if bt.lchild is not None:
stack1.append(bt.lchild)
if bt.rchild is not None:
stack1.append(bt.rchild)
# print result
while len(stack2) != 0:
print(stack2.pop().key, end=" ")
else:
print()
# output:
# post-order:
# 4 2 5 6 3 1
2.3 python-二叉树遍历 ->宽度优先遍历
def widthTrave(self, bt):
print("width-first: ")
if bt is not None:
queue = []
queue.append(bt)
while len(queue) != 0:
bt = queue.pop(0)
print(bt.key, end=" ")
if bt.lchild is not None:
queue.append(bt.lchild)
if bt.rchild is not None:
queue.append(bt.rchild)
else:
print()
# output:
# width-first:
# 1 2 3 4 5 6
2.4 python-二叉树遍历 ->完整体
将上面的代码整合在一起方便查看:
点击查看代码
class BTNode():
def __init__(self, key=None, lchild=None, rchild=None):
self.key = key
self.lchild = lchild
self.rchild = rchild
class BiTree():
def __init__(self, data_list):
self.data = iter(data_list)
def createBiTree(self, bt=None):
try:
next_data = next(self.data)
if next_data == '#':
bt = None
else:
bt = BTNode(next_data)
bt.lchild = self.createBiTree(bt.lchild)
bt.rchild = self.createBiTree(bt.rchild)
except Exception as e:
print(e)
return bt
# ----------递归------------ #
# 先序遍历
def preOrderTrave(self, bt):
if bt is not None:
print(bt.key, end=" ")
self.preOrderTrave(bt.lchild)
self.preOrderTrave(bt.rchild)
# 中序遍历
def inOrderTrave(self, bt):
if bt is not None:
self.inOrderTrave(bt.lchild)
print(bt.key, end=" ")
self.inOrderTrave(bt.rchild)
# 后序遍历
def postOrderTrave(self, bt):
if bt is not None:
self.postOrderTrave(bt.lchild)
self.postOrderTrave(bt.rchild)
print(bt.key, end=" ")
# ----------非递归------------ #
# 先序
def preOrderTrave2(self, bt):
print("pre-order: ")
if bt is not None:
stack = []
stack.append(bt)
while len(stack) != 0:
bt = stack.pop()
print(bt.key, end=" ")
if bt.rchild is not None:
stack.append(bt.rchild)
if bt.lchild is not None:
stack.append(bt.lchild)
else:
print()
# 中序
def inOrderTrave2(self, bt):
print("in-order: ")
if bt is not None:
stack = []
while len(stack) != 0 or bt is not None:
if bt is not None:
stack.append(bt)
bt = bt.lchild
else:
bt = stack.pop()
print(bt.key, end=" ")
bt = bt.rchild
else:
print()
# 后序
def postOrderTrave2(self, bt):
print("post-order: ")
if bt is not None:
stack1 = [] # somebody come and go
stack2 = [] # root + right + left
stack1.append(bt)
while len(stack1) != 0:
bt = stack1.pop()
stack2.append(bt)
if bt.lchild is not None:
stack1.append(bt.lchild)
if bt.rchild is not None:
stack1.append(bt.rchild)
# print result
while len(stack2) != 0:
print(stack2.pop().key, end=" ")
else:
print()
# 宽度优先遍历
def widthTrave(self, bt):
print("width-first: ")
if bt is not None:
queue = []
queue.append(bt)
while len(queue) != 0:
bt = queue.pop(0)
print(bt.key, end=" ")
if bt.lchild is not None:
queue.append(bt.lchild)
if bt.rchild is not None:
queue.append(bt.rchild)
else:
print()
# test:
data_list = [1, 2, '#', 4, '#', '#', 3, 5, '#', '#', 6, '#', '#']
biTree = BiTree(data_list) # biTree -> BiTree class, iter
root = biTree.createBiTree() # root -> createBiTree()'s return
biTree.preOrderTrave2(root)
print('\n')
biTree.inOrderTrave2(root)
print('\n')
biTree.postOrderTrave2(root)
print('\n')
biTree.widthTrave(root)
💡每日提醒:
太多事情要做,别急,一件一件来,集中精神,慢就是快。
总之,搞清楚自己在干嘛,不要盲目!不要盲目!不要盲目!