Leetcode—426. 将二叉搜索树转化为排序的双向链表【中等】Plus

2024每日刷题(148)

Leetcode---426. 将二叉搜索树转化为排序的双向链表

实现代码

cpp 复制代码
/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;

    Node() {}

    Node(int _val) {
        val = _val;
        left = NULL;
        right = NULL;
    }

    Node(int _val, Node* _left, Node* _right) {
        val = _val;
        left = _left;
        right = _right;
    }
};
*/

class Solution {
public:
    Node* treeToDoublyList(Node* root) {
        if(root == nullptr) {
            return (Node*)nullptr;
        }

        // 中序遍历
        stack<Node*> st;
        Node* first = nullptr;
        Node* pre = nullptr;

        while(root != nullptr || !st.empty()) {
            // 左子树全部入栈
            while(root != nullptr) {
                st.push(root);
                root = root->left;
            }

            root = st.top(), st.pop();
            if(first == nullptr) {
                first = root;
            }

            if(pre != nullptr) {
                pre->right = root;
                root->left = pre;
            }

            pre = root;
            root = root->right;
        }

        first->left = pre;
        pre->right = first;
        return first;
    }
};

运行结果

之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

相关推荐
用户204937554954 分钟前
端侧语音部署踩坑:模型能跑不等于终端真的能用
后端·算法
shehuiyuelaiyuehao25 分钟前
算法39,位运算,消失的两个数字
java·数据结构·算法
ZiLing26 分钟前
2026 ROS 2 Lyrical 踩坑实录(一):编译与依赖——rosdep、现代 CMake 与 CMake 4.x
算法
Murphy_lx27 分钟前
1124. 表现良好的最长时间段
c++·算法
aramae38 分钟前
模拟实现strstr函数(C语言)
c语言·开发语言·算法
liliangcsdn1 小时前
因子权重矩阵处理-滞回缓冲带+降频稳定化动态重选
开发语言·python·算法
敲代码的嘎仔1 小时前
自己设计了一个兑换码算法:自增ID + Base32转码 + 按位加权签名 + 异或混淆,面试被追问细节时终于不用慌了
java·数据库·mysql·算法·微服务·面试·职场和发展
云析赢指标公式网42 小时前
文华WH6布林轨道均线强弱共振指标公式
前端·算法
多弗朗皮卡丘2 小时前
数据结构4:链表(下)
c语言·数据结构·链表
luj_17683 小时前
一线一区一变破解人盯人防守密码
开发语言·网络·c++·经验分享·算法