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;
    }
};

运行结果

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

相关推荐
朝朝辞暮i36 分钟前
C++ 第 28 课:Lambda 表达式
开发语言·c++·算法
代码什么用39 分钟前
LeetCode-560.和为 K 的子数组
算法·leetcode
All for pursuit.43 分钟前
【回溯-3】39.组合总和
数据结构·c++·算法·leetcode
释厄6231 小时前
BSD 基础论——不要忘记连接·不要停滞循环·AI基础算法
人工智能·算法
见叶之秋1 小时前
【C++】一条双向链的诞生:手写 list 模拟实现
c++
沫璃染墨1 小时前
《从零入门Linux系统篇(五十六):线程篇·九——生产者消费者模型:从条件变量到BlockingQueue实现》
linux·服务器·c++·驱动开发·设计模式·架构·系统架构
张小姐的猫1 小时前
【Linux】网络编程 —— 五种IO模型
linux·运维·服务器·网络·c++·人工智能·php
yi0111 小时前
DAY19: LeetCode 28 找出字符串中第一个匹配项的下标
人工智能·笔记·python·算法·leetcode
不会就选b1 小时前
算法日常・每日刷题--<动态规划>6
数据结构·算法·leetcode
lhbweilai1 小时前
深挖FreeRTOS内核实现(上)
stm32·单片机·链表