# https://blog.csdn.net/yuesoda/article/details/89925738
# 树
class Node:
def __init__(self, root, left=None, right=None):
self.root = root
self.left = left
self.right = right
# 树深度
def max_depth(tree):
if not tree:
return 0
return max(max_depth(tree.left), max_depth(tree.right))+1
# 前序遍历
def pre_order(tree):
if not tree:
return
print(tree.root, end=' ')
pre_order(tree.left)
pre_order(tree.right)
# 中序遍历
def mid_order(tree):
if not tree:
return
mid_order(tree.left)
print(tree.root, end=' ')
mid_order(tree.right)
# 后序遍历
def post_order(tree):
if not tree:
return
post_order(tree.left)
post_order(tree.right)
print(tree.root, end=' ')
# 层次遍历
def bfs(tree):
if not tree:
return
queue = [] # 队列先进先出
queue.append(tree)
while queue:
cur_node = queue.pop(0)
print(cur_node.root, end=' ')
if cur_node.left is not None:
queue.append(cur_node.left)
if cur_node.right is not None:
queue.append(cur_node.right)
# 深度遍历
def dfs(tree):
if not tree:
return
print(tree.root, end=' ')
dfs(tree.left)
dfs(tree.right)
# 深度遍历
def dfs_stack(tree):
if not tree:
return
stack = []
stack.append(tree)
while stack:
cur_node = stack.pop()
print(cur_node.root, end=' ')
if cur_node.right is not None:
stack.append(cur_node.right)
if cur_node.left is not None:
stack.append(cur_node.left)
# 中序遍历
def mid_order_stack(tree):
stack=[]
while stack or tree:
while tree:
stack.append(tree)
tree=tree.left
tree=stack.pop()
print(tree.root, end=' ')
tree=tree.right
# 后序遍历
def post_order_stack(tree):
if not tree:
return
stack = []
stack.append(tree)
res = []
while stack:
cur_node = stack.pop()
if cur_node.left is not None:
stack.append(cur_node.left)
if cur_node.right is not None:
stack.append(cur_node.right)
res.append(cur_node.root)
for i in res[::-1]:
print(i, end=' ')
tree = Node(5, Node(3,Node(2),Node(4)), Node(7,Node(6)))
print('deepth of the tree: \n', max_depth(tree))
print('pre_order: ')
pre_order(tree)
print('\nmid_order: ')
mid_order(tree)
print('\nmid_order_stack: ')
mid_order_stack(tree)
print('\npost_order: ')
post_order(tree)
print('\npost_order_stack: ')
post_order_stack(tree)
print('\nlevel_order: ')
bfs(tree)
print('\ndeep_order: ')
dfs(tree)
print('\ndeep_order: ')
dfs_stack(tree)
2021-01-26 二叉树搜索
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 1. 树结构示意图 补充: 兄弟节点:具有相同父节点的节点互称为兄弟节点。 树的深度:从根节点开始(其深度为0)自...
- 满二叉树: 除最后一层无任何子节点外,每一层上的所有结点都有两个子结点 完全二叉树: 完全二叉树是由满二叉树而引出...
- 1、概念 搜索二叉树(Binary Search Tree - BST) 它的左子树不空,则左子树上所有结点的值均...
- 1、二叉树 每个结点最多只有两个子树的树结构 2、BST(二叉搜索树或二叉排序树) 左子树上所有结点的值均小于它的...
- 1从上往下打印二叉树 【题目】从上往下打印出二叉树的每个节点,同层节点从左至右打印。 【考察点】举例让抽象具体...