binarytree二叉树节点DFS深度优先搜索遍历,递归,python
import random
from binarytree import build
def app():
data = []
for i in range(13):
data.append(i)
random.shuffle(data)
root = build(data)
root.pprint(index=True, delimiter=',')
paths = []
print('-----')
my_dfs_travel(root, paths)
print('深度遍历', paths)
# 深度遍历,从左至右,递归实现
def my_dfs_travel(root, paths):
if root == None:
return
paths.append(root.value)
if root.left != None:
my_dfs_travel(root.left, paths)
if root.right != None:
my_dfs_travel(root.right, paths)
if __name__ == '__main__':
app()
输出:
________________0,7_______________
/ \
_____1,6______ ______2,5_
/ \ / \
__3,4_ __4,0__ __5,2_ 6,9
/ \ / \ / \
7,12 8,3 9,11 10,10 11,8 12,1
-----
深度遍历 [7, 6, 4, 12, 3, 0, 11, 10, 5, 2, 8, 1, 9]
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/zhangphil/article/details/121318291
内容来源于网络,如有侵权,请联系作者删除!