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

二叉搜索树insert方法异常导致中序遍历输出顺序错误问题求助

BST插入功能错误修复方案

核心错误原因

insert方法查找插入位置时没有从根节点出发,而是基于类成员变量current的遗留值遍历,导致新节点挂载位置完全不符合BST的结构规则,因此中序遍历输出顺序错误。

具体错误点

  • 原insert初始化遍历指针时错误使用current赋值:BSTNode<T> p = current, q = current;,current是之前操作的残留位置,不是整棵树的根节点,无法遍历到正确的插入位置
  • 挂载新节点时错误使用current作为父节点,而非遍历过程中记录的实际父节点

修复后的insert代码

public boolean insert(int key, T val) {
    // 每次插入都从根节点开始遍历找位置
    BSTNode<T> p = root, q = root;

    while (p != null) {
        q = p;
        if (p.key == key) {
            // 重复key插入失败
            return false;
        } else if (key < p.key)
            p = p.left;
        else
            p = p.right;
    }

    BSTNode<T> newNode = new BSTNode<T>(key, val);
    if (empty()) {
        root = current = newNode;
        return true;
    } else {
        // 用遍历得到的父节点q挂载新节点
        if (key < q.key)
            q.left = newNode;
        else
            q.right = newNode;
        current = newNode;
        return true;
    }
}

验证说明

修复后插入节点时会从根节点遍历到正确的叶子节点位置挂载新节点,符合BST的结构规则,中序遍历即可输出升序排列的key序列。

内容的提问来源于stack exchange,提问作者Hatem Alamri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 22:45:06