BST二叉搜索树查找节点元素,binarytree,Python
  TEZNKK3IfmPf 2023年11月14日 79 0

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)]
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年05月31日   38   0   0 python开发语言
  TEZNKK3IfmPf   2024年05月31日   28   0   0 python
  TEZNKK3IfmPf   2024年05月31日   30   0   0 python
TEZNKK3IfmPf