Java二叉搜索树代码无输出问题求助:无法定位错误原因
二叉搜索树无中序遍历输出的问题排查与修复
核心错误原因
你的代码存在两个关键问题,直接导致无输出:
- 非法包名:Java包名不允许包含空格,
package binary tree;不符合语法规范,会引发编译错误。 - 静态root被意外重置:
root是类的静态成员变量,main方法中先通过run()调用静态insert方法把节点插入到root,但随后new BinarySearchTree()触发的构造函数里,root = null;会将已存储节点的静态root直接置空,导致中序遍历时没有节点可遍历。
修复后的代码
// 修正包名,单个文件运行时也可直接删除包声明 package binarytree; import java.util.Scanner; public class BinarySearchTree { // 将root改为实例变量,避免静态变量的全局干扰 private Node root; BinarySearchTree() { this.root = null; } static class Node { int value; Node left; Node right; public Node(int value) { this.value = value; } public void display() { System.out.print(value + " "); } } // 改为实例方法,操作当前对象的root public void insert(int value) { root = insert(root, value); } private Node insert(Node node, int value) { if (node == null) { node = new Node(value); } else if (value < node.value) { node.left = insert(node.left, value); } else if (value > node.value) { node.right = insert(node.right, value); } return node; } // 重构run方法,直接创建实例并插入节点 public static BinarySearchTree run() { Scanner scan = new Scanner(System.in); BinarySearchTree bst = new BinarySearchTree(); int nodeSize = scan.nextInt(); int nodeValue; System.out.println("Enter Node Values:"); for (int i = 0; i < nodeSize; i++) { nodeValue = scan.nextInt(); bst.insert(nodeValue); } scan.close(); return bst; } public void inOrder() { inOrder(root); } private void inOrder(Node node) { if (node != null) { inOrder(node.left); node.display(); inOrder(node.right); } } public static void main(String args[]) { BinarySearchTree bst = run(); bst.inOrder(); } }
关键修改说明
- 把静态
root改为实例成员变量,每个BinarySearchTree对象拥有独立根节点,避免静态变量的全局干扰。 - 将
insert调整为实例方法,操作当前对象的根节点。 - 重构
run方法,直接创建树实例并完成节点插入,返回实例供后续遍历使用。 - 修正包名,确保符合Java语法规范。
内容的提问来源于stack exchange,提问作者newton
相关产品推荐
相关产品推荐

