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

基于文本文件创建与搜索BST遇阻,寻求Java代码指导

Troubleshooting Your BST Implementation for Name-Count Data

Hey there! First time building a Binary Search Tree (BST) can feel super overwhelming—great job diving in and trying to implement it yourself. Let's break down the key issues in your code and walk through how to fix them, plus give you some direction for moving forward.

1. Critical Bug in BST Insert Logic (addNode Method)

Your addNode method has a major structural issue with the while loop—your else block (for names greater than the current focus node) is incorrectly nested inside the if block. This means you'll never properly traverse the right subtree for insertion. Here's what's wrong:

// Original broken logic
if (name.compareTo(focusNode.name) < 0) {
    focusNode = focusNode.leftChild;
    if (focusNode == null) {
        parent.leftChild = newNode;
        return;
    }
    // This else is INSIDE the if, which is wrong!
    else {
        focusNode = focusNode.rightChild;
        if (focusNode == null) {
            parent.rightChild = newNode;
            return;
        }
    }
}

Fixed Insert Logic

The else block (handling names >= current node) needs to be at the same level as the if block. Here's the corrected addNode:

public void addNode(String name, int data) {
    Node newNode = new Node(name, data);
    if (root == null) {
        root = newNode;
        return;
    }

    Node focusNode = root;
    Node parent;

    while (true) {
        parent = focusNode;
        int comparison = name.compareTo(focusNode.name);
        if (comparison < 0) {
            // Move to left subtree
            focusNode = focusNode.leftChild;
            if (focusNode == null) {
                parent.leftChild = newNode;
                return;
            }
        } else {
            // Move to right subtree (handles equal or greater)
            focusNode = focusNode.rightChild;
            if (focusNode == null) {
                parent.rightChild = newNode;
                return;
            }
        }
    }
}

2. File Reading & Data Parsing Issues

Your file reading code has several bugs that will cause incorrect data to be inserted into the tree:

  • Skipping every other line: You call reader.readLine() in the while condition AND again inside the loop, which means you're discarding half of your lines.
  • Incorrect name extraction: The condition c >= '0' || c <= '9' is backwards (should be &&), and you keep overwriting name for every character in the line. You should stop at the first digit you find.
  • Redundant search inside loop: You're searching for "Buffy " (with a trailing space) inside the file reading loop—this should run after you've built the tree, not on every iteration.

Fixed File Reading Code

public static void main(String[] args) throws Exception {
    BinarySearchTree tree = new BinarySearchTree();
    FileReader file = new FileReader("/Users/mattspahr/Desktop/test.txt");
    BufferedReader reader = new BufferedReader(file);
    String str;

    // Read lines correctly without skipping
    while ((str = reader.readLine()) != null) {
        String name = null;
        String num = null;

        // Find the first occurrence of a digit to split name and count
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c >= '0' && c <= '9') { // Fixed condition here
                name = str.substring(0, i).trim(); // Trim whitespace from name
                num = str.substring(i).trim(); // Extract digits directly
                break; // Stop once we find the first digit
            }
        }

        // Handle cases where no digits are found (optional error handling)
        if (name == null || num == null) {
            System.out.println("Skipping invalid line: " + str);
            continue;
        }

        int data = Integer.parseInt(num);
        tree.addNode(name, data);
    }

    // Search AFTER building the tree
    Node n = tree.searchName("Buffy"); // Remove trailing space unless your data has it
    if (n != null) {
        System.out.println("Found: " + n.name + " - Count: " + n.data);
    } else {
        System.out.println("Name not found.");
    }

    reader.close(); // Don't forget to close the reader!
}

3. Other Small but Important Fixes

  • Static Inner Node Class: Your Node class is a non-static inner class, which means you can't create instances of Node without an instance of BinarySearchTree (this would cause errors in some contexts). Make it static:
    public static class Node {
        String name;
        int data;
        Node leftChild;
        Node rightChild;
    
        public Node(String n, int d) {
            name = n;
            data = d;
        }
    
        // Add a toString method to print node info nicely
        @Override
        public String toString() {
            return name + ": " + data;
        }
    }
    
  • Null Safety in searchName: If the tree is empty (root is null), your current searchName method will throw a NullPointerException. Add a check at the start:
    public Node searchName(String name) {
        if (root == null) {
            return null;
        }
    
        Node focusNode = root;
        while (!focusNode.name.equals(name)) {
            int comparison = name.compareTo(focusNode.name);
            if (comparison < 0) {
                focusNode = focusNode.leftChild;
            } else {
                focusNode = focusNode.rightChild;
            }
            if (focusNode == null) {
                return null;
            }
        }
        return focusNode;
    }
    

Learning & Debugging Tips for Moving Forward

  • Manual Simulation: Grab a piece of paper and manually walk through inserting 3-4 names into your BST—this will help you visualize how the traversal should work.
  • Test with Small Data: Start with a tiny test.txt file (2-3 lines) instead of your full dataset. This makes it easier to track what's being inserted and debug.
  • Use Debugging Tools: In your IDE, set breakpoints in addNode and searchName to step through each line and see where the logic deviates from what you expect.
  • Case Sensitivity: Remember that String.compareTo() is case-sensitive. If your dataset has mixed case names (e.g., "buffy" and "Buffy"), they'll be treated as different keys. Consider normalizing names to lowercase/uppercase before insertion/search.

内容的提问来源于stack exchange,提问作者School Mail

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 08:57:45