You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何读取txt文件数据构建BST并仅展示树的前4层结构

单词BST构建与前4层结构输出实现

现有BST类的插入、搜索逻辑可直接复用,只需补充文件读取、限层打印两个模块即可完成需求,完整实现如下:

基础依赖补全

代码中继承的BinaryTree基类、使用的Node节点类需要先定义,否则原有逻辑无法运行:

class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

class BinaryTree:
    def __init__(self, root=None):
        self.root = root

原有BST核心代码

保留已编写的插入、搜索逻辑即可:

class BinarySearchTree(BinaryTree):
    def insert(self, value):
        parent = None
        x = self.root
        while(x):
            parent = x
            if value < x.data:
                x = x.left
            else:
                x = x.right
        if parent is None:
            self.root = Node(value)
        elif value < parent.data:
            parent.left = Node(value)
        else:
            parent.right = Node(value)

    def search(self, value):
        return self._search(value, self.root)

    def _search(self, value, node):
        if node is None:
            return node
        if node.data == value:
            return BinarySearchTree(node)
        if value < node.data:
            return self._search(value, node.left)
        return self._search(value, node.right)

新增功能实现

  • 单词文件读取:读取指定txt文件内的所有单词,统一格式化后逐个插入BST,避免大小写、前后标点影响排序结果
  • 限层结构打印:采用层序遍历控制遍历深度,根节点记为第1层,仅遍历输出前4层节点,空节点标记为None方便识别结构
from collections import deque

def build_bst_from_word_file(file_path):
    bst = BinarySearchTree()
    with open(file_path, 'r', encoding='utf-8') as f:
        # 兼容空格、换行分隔的单词格式
        raw_content = f.read()
        words = [word.strip('.,!?;:\'\"()[]').lower() for word in raw_content.split()]
        for word in words:
            if word:
                bst.insert(word)
    return bst

def print_bst_layers(root, max_depth=4):
    if not root:
        print("空树")
        return
    task_queue = deque([(root, 1)])
    current_depth = 1
    current_layer_nodes = []

    while task_queue:
        node, depth = task_queue.popleft()
        if depth > max_depth:
            break
        if depth != current_depth:
            print(f"第{current_depth}层节点:{' | '.join(current_layer_nodes)}")
            current_layer_nodes = []
            current_depth = depth
        current_layer_nodes.append(node.data if node else 'None')
        if node:
            task_queue.append((node.left, depth + 1))
            task_queue.append((node.right, depth + 1))
    # 输出最后一层的内容
    if current_layer_nodes and current_depth <= max_depth:
        print(f"第{current_depth}层节点:{' | '.join(current_layer_nodes)}")

调用方式

将存储单词的txt文件放在脚本同级目录,执行以下代码即可:

if __name__ == "__main__":
    # 替换为你的单词文件路径
    word_bst = build_bst_from_word_file("words.txt")
    print("BST前4层结构:")
    print_bst_layers(word_bst.root, max_depth=4)

排序规则说明:字符串比较默认遵循Python内置字典序,和常规英文单词排序逻辑一致;如果需要调整排序规则,修改insert方法中的大小判断逻辑即可。

内容的提问来源于stack exchange,提问作者Looks Brum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.02 08:09:42