深度优先、广度优先
作者:互联网
'''
1
/ \
2 3
/ \
4 5
'''
class TreeNode:
def __init__(self,val):
self.val = val
self.left = None
self.right = None
# 深度优先-先序遍历
def dfs_pre(node):
if not node:
return
print(node.val)
dfs_pre(node.left)
dfs_pre(node.right)
# 深度优先-中序遍历
def dfs_mid(node):
if not node:
return
dfs_mid(node.left)
print(node.val)
dfs_mid(node.right)
# 深度优先-后序遍历
def dfs_dec(node):
if not node:
return
dfs_dec(node.left)
dfs_dec(node.right)
print(node.val)
# 广度优先,列表版
def bfs(node):
q = [(node,0)]
while q:
node,level = q.pop(0)
if node is None:
continue
print(node.val)
q.append((node.left,level+1))
q.append((node.right,level+1))
from collections import deque
# 广度优先,双端队列版
def bfs(node):
q = deque([(node,0)])
while q:
node,level = q.popleft()
if node is None:
continue
print(node.val)
q.append((node.left,level+1))
q.append((node.right,level+1))
def main():
root = TreeNode(1)
n1 = TreeNode(2)
n2 = TreeNode(3)
n3 = TreeNode(4)
n4 = TreeNode(5)
root.left = n1
root.right = n2
n1.left = n3
n1.right = n4
print("深度优先-先序遍历".center(20,"="))
dfs_pre(root)
print("深度优先-中序遍历".center(20,"="))
dfs_mid(root)
print("深度优先-后序遍历".center(20,"="))
dfs_dec(root)
print("广度优先".center(20,"="))
bfs(root)
if __name__ == "__main__":
main()
标签:node,优先,right,val,dfs,深度,print,广度,left 来源: https://www.cnblogs.com/ray-mmss/p/16626047.html