您的位置:首页 > 编程语言 > Python开发

python二叉树的深度优先遍历和广度优先遍历

2019-03-16 18:15 106 查看

二叉树的实现

# 设计实现二叉树,首先需要一个节点类和树类
# 并且需要对节点类和树类实例化,树需要一个add方法把新的节点加进去
class Node(object):
def __init__(self, number):
self.number = number
self.rchild = None
self.lchild = None

class Tree(object):
list = []

def __init__(self):
self.root = None

def add(self, number):
node = Node(number)
# 首先判断树是否为空
if not self.root:
self.root = node
Tree.list.append(self.root)
else:
# 使用list模拟队列,root和左右子节点依次入队列

while True:
point = Tree.list[0]

if not point.lchild:
point.lchild = node
Tree.list.append(point.lchild)
return
elif not point.rchild:
point.rchild = node
Tree.list.append(point.rchild)
Tree.list.pop(0)
return

# add基本逻辑就是利用队列依次保存未满状态的节点,然后通过不断取队头point来添加左右
# 孩子,并把左右孩子加入队列,插入完后检查是否左右孩子都有了,依然未满,则保留,
# 满了,则退出队列list.pop(0),取下一个队首。

if __name__ == '__main__':
t = Tree()
L = [1, 2, 3, 4, 5, 6, 7]
for x in L:
t.add(x)
print('success')

二叉树插入节点的基本思路是:
首先判断根结点是否存在,如果不存在则插入根节点。然后判断左节点是否存在,如果不存在则插入左节点。然后判断右节点是否存在,如果不存在则插入右节点。接着,依次判断左右节点的子节点,直到插入成功。
体现了广度优先的思想,层层遍历。

深度优先遍历:递归实现
广度优先遍历:栈或者队列

深度优先考察递归,当子节点为空时,递归结束。
广度优先考察队列的结构,消除父节点,父节点出队列顺便打印,子节点入队列,当队列内元素为0时,遍历结束。

深度优先
深度优先遍历包括前序遍历,中序遍历,后序遍历。采用递归的方法。

# 深度优先遍历,用递归的方法
def shendu(root):
if not root:
return []

result = []
while root:
result.append(root)
if root.left is not None:
shendu(root.left)
if root.right is not None:
shendu(root.right)
return result

广度优先

# 广度优先遍历,用队列实现
def guangdu(root):
if not root:
return []

result = []
my_queue = []
my_queue.append(root)
while my_queue:
node = my_queue.pop(0)
result.append(node.val)
if node.left:
my_queue.append(node.left)
if node.right:
my_queue.append(node.right)

return result

用两个队列,一个存放节点,一个存放值。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: