binarytree二叉树节点DFS深度优先搜索遍历,递归,python

x33g5p2x  于2021-12-30 转载在 Python  
字(0.6k)|赞(0)|评价(0)|浏览(218)

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]

相关文章