将一个搜索二叉树转为升序的双链表

这篇博客详细介绍了如何将一棵二叉树转换为一个双链表,通过递归函数`binary_tree_to_list_part`实现了这个过程。首先检查根节点是否为空,然后遍历树的左子树,接着连接当前节点到链表末尾,再处理右子树,最后返回链表的最后一个节点。整个转换过程确保了节点的正确连接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

typedef struct binary_node {
    node_t* left;
    node_t* right;
    int value;
} node_t;

int binary_tree_to_list(node_t* pRoot) {
    if (pRoot == nullptr) {
        return 0;
    }

    node_t* pListLastNode = nullptr;

    binary_tree_to_list_part(pRoot, &pListLastNode);

    while (pListLastNode->right != nullptr) {
        pListLastNode = pListLastNode->right;
    }

    return pListLastNode;
}

// 该函数功能是将一颗二叉树转换为双链表,并将其与pListLastNode链接在一起
void binary_tree_to_list_part(node_t* pRoot, node_t** pListLastNode) {
    if (pRoot == nullptr) {
        return;
    }

    if (pRoot->left != nullptr) {
        binary_tree_to_list_part(pRoot->left, pListLastNode);
    }

    node_t* pCurrent = pRoot;
    pCurrent->left = *pListLastNode;
    if (*pListLastNode != nullptr) {
        (*pListLastNode)->right = pCurrent;
    }
    *pListLastNode = pCurrent;

    if (pRoot->right != nullptr) {
        binary_tree_to_list_part(pRoot->right, pListLastNode);
    }

    return;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值