BST二叉搜索树查找节点元素,binarytree,Python

x33g5p2x  于2021-12-07 转载在 Python  
字(0.7k)|赞(0)|评价(0)|浏览(291)

BST二叉搜索树查找节点元素,binarytree,Python

import random

import binarytree

def app():
    t = binarytree.bst(height=5, is_perfect=False)
    print(t)
    print('-----')
    idx = random.randint(1, t.size - 1)
    target = t.levelorder[idx].value  # 从节点中随机找一个值
    print('查找', target)
    path = search(t, target)
    print('路线', path)

def search(node, target):
    path = []

    while True:
        path.append(node)

        if node.value == target:
            break

        if node is not None:
            if target > node.value:
                node = node.right
            else:
                node = node.left

    return path

if __name__ == '__main__':
    app()

运行日志输出:

__2__________________________________
 /                                     \
0                    ___________________60___
 \                  /                        \
  1       _________36______                  _62
         /                 \                /
        4___            ____39___          61
       /    \          /         \
      3     _31       37         _45
           /   \        \       /   \
          23    33       38    43    49

-----
查找 45
路线 [Node(2), Node(60), Node(36), Node(39), Node(45)]

相关文章