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

二叉树中inorderSuccessor函数返回NULL的问题排查求助

二叉树中序后继函数返回NULL问题排查

我实现了二叉树的getMin_Node与inorderSuccessor函数,调用inorder_min_test测试时,inorderSuccessor返回NULL,无法遍历后续节点。以下是相关代码与测试输出:

测试函数代码

// 该方法通过打印测试getMin_Node()和inorderSuccessor()
void inorder_min_test(String * str){
    String *min = getMin_Node(str);

    while(min != nullptr){
        cout << "NEXT IS ===> " << min->getStr() << endl;
        cout << "before inorder" << str << ", " << min << endl;
        min = inorderSuccessor(str, min);
        if(min == nullptr) {
            cout << "MINIMUM NODE IS NULL " << endl;
        }
    }
}

获取最小节点函数

// 返回最小节点
String* getMin_Node(String* node) {
    if(node->left != nullptr){
        node = getMin_Node(node->left);
    }
    return node;
}

中序后继节点函数

// 返回后继节点
String* inorderSuccessor(String* root, String* p) {
    String* temp = NULL;

    while (root != NULL){
        if(p < root){  // <-- 已重载operator < ()
            temp = root;
            root = root->left;
        }
        else{
            root = root->right;
        }
    }

    cout << temp << endl;
    return temp;
}

测试输出结果

NEXT IS ===> MAN
before inorder 0x13c704080, 0x13c704080
0x0
MINIMUM NODE IS NULL 

注:String是包含C风格字符串的节点,已重载<运算符用于节点值比较。


问题原因与修复方案

当前inorderSuccessor逻辑缺失了节点存在右子树的核心场景:
中序后继的正确逻辑分为两种情况:

  1. 若目标节点p存在右子树,其后继是右子树的最小节点;
  2. 若p无右子树,才需要从根节点出发,寻找第一个值大于p的祖先节点。

原代码只处理了第二种情况,且循环未正确终止(未处理root == p的场景),导致无法正确找到后继。

修复后的inorderSuccessor函数:

String* inorderSuccessor(String* root, String* p) {
    // 情况1:p有右子树,后继为右子树的最小节点
    if (p->right != nullptr) {
        return getMin_Node(p->right);
    }

    // 情况2:p无右子树,寻找第一个值大于p的祖先
    String* temp = nullptr;
    while (root != nullptr) {
        if (*p < *root) {  // 明确是值比较,避免指针地址误判
            temp = root;
            root = root->left;
        } else if (*root < *p) {
            root = root->right;
        } else {
            // 找到p节点,终止循环
            break;
        }
    }
    return temp;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 10:30:52