如何创建BST类实例调用insert等方法实现二叉搜索树相关功能
BST代码问题修复说明
你代码存在3处核心错误,对应修复方案如下:
核心错误列表
- 构造函数调用错误:你定义的
Algo_BST构造器要求传入int类型的根节点初始值,但是main方法中创建实例时没有传参,属于基础编译错误 - 查找逻辑写反:
contains方法中,当目标值大于当前节点值时,应该去右子树查找,你的代码写反为查询左子树,会直接导致查找功能失效 - 打印逻辑不符合预期:
insert方法返回的是根节点对象,你直接打印insert的返回值只会固定输出根节点的值,看不到新插入节点的内容,也无法验证整棵树的结构是否正确
修复后完整代码
class BST { static class Algo_BST { public int value; public Algo_BST left; public Algo_BST right; public Algo_BST(int value) { this.value = value; } public Algo_BST insert(int value) { if(value < this.value){ if(left == null){ left = new Algo_BST(value); }else{ left.insert(value); } }else{ if(right == null){ right = new Algo_BST(value); }else{ right.insert(value); } } return this; } public boolean contains(int value) { // 修复查找方向逻辑 if (this.value < value){ if(right == null){ return false; }else{ return right.contains(value); } }else if(this.value > value){ if(left == null){ return false; }else{ return left.contains(value); } }else{ return true; } } // 新增中序遍历方法,BST中序遍历结果为升序,可直接验证插入逻辑是否正确 public void inOrderTraverse() { if (this.left != null) { this.left.inOrderTraverse(); } System.out.print(this.value + " "); if (this.right != null) { this.right.inOrderTraverse(); } } public String toString() { return "Data: " + this.value; } } public static void main(String[] args) { // 修复构造函数调用,传入根节点初始值90 BST.Algo_BST bst = new BST.Algo_BST(90); bst.insert(50); bst.insert(70); bst.insert(80); // 打印中序遍历结果验证插入正确性 System.out.print("BST中序遍历结果(升序):"); bst.inOrderTraverse(); System.out.println(); System.out.println("是否包含80:"+bst.contains(80)); System.out.println("是否包含1000:"+bst.contains(1000)); } }
运行结果
BST中序遍历结果(升序):50 70 80 90 是否包含80:true 是否包含1000:false
内容的提问来源于stack exchange,提问作者Respawn
相关产品推荐
相关产品推荐

