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

Posted zhangphil

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了BST二叉搜索树查找节点元素,binarytree,Python相关的知识,希望对你有一定的参考价值。

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)]

以上是关于BST二叉搜索树查找节点元素,binarytree,Python的主要内容,如果未能解决你的问题,请参考以下文章

二叉搜索树BST广度优先搜索遍历BFS计算树高度,非递归,binarytree,python

二叉搜索树BST图节点平衡因子计算,binarytree,Python

BST二叉搜索树插入一个节点后检测距离当前节点最近的失衡点,binarytree,Python

BST二叉搜索树插入一个节点后检测距离当前节点最近的失衡点,binarytree,Python

二叉搜索树BST节点DFS深度优先搜索遍历,基于栈,非递归,binarytree,python

数据结构二叉树(BT),二叉查找树(BST),平衡二叉树(AVL树)