当前位置:网站首页>剑指Offer 36.二叉搜索树与双向链表 中序遍历
剑指Offer 36.二叉搜索树与双向链表 中序遍历
2022-08-02 03:33:00 【HotRabbit.】
题目
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的循环双向链表。要求不能创建任何新的节点,只能调整树中节点指针的指向。
为了让您更好地理解问题,以下面的二叉搜索树为例:
我们希望将这个二叉搜索树转化为双向循环链表。链表中的每个节点都有一个前驱和后继指针。对于双向循环链表,第一个节点的前驱是最后一个节点,最后一个节点的后继是第一个节点。
下图展示了上面的二叉搜索树转化成的链表。“head” 表示指向链表中有最小元素的节点。
特别地,我们希望可以就地完成转换操作。当转化完成以后,树中节点的左指针需要指向前驱,树中节点的右指针需要指向后继。还需要返回链表中的第一个节点的指针。
**注意:**本题与主站 426 题相同:https://leetcode-cn.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list/
**注意:**此题对比原题有改动。
Related Topics
- 栈
- 树
- 深度优先搜索
- 二叉搜索树
- 链表
- 二叉树
- 双向链表
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
使用中序遍历,最左边节点一定在开头,深度优先遍历从最左下节点开始
定义一个pre记录前驱节点,如果pre == null ,那么到达最左下角节点,记录为head 头节点。如果 pre != null,pre 的后继节点为 cur(当前节点),cur 的前驱节点为 pre。
中序遍历:
void dfs(Node cur){
if (cur == null) return;
dfs(cur.left);
dfs(cur);
dfs(cur.right);
}
题解
class Solution {
Node pre,head;
public Node treeToDoublyList(Node root) {
if (root == null) return null;
dfs(root);
head.left = pre;
pre.right = head;
return head;
}
void dfs(Node cur){
if (cur == null) return;
dfs(cur.left);
if (pre != null) pre.right = cur;
else head = cur;
cur.left = pre;
pre = cur;
dfs(cur.right);
}
}
边栏推荐
- 【Arduino connects DHT11 humidity and temperature sensor】
- How to quickly build your own IoT platform?
- 【plang 1.4.5】编写坦克(双人)游戏脚本
- 【plang 1.4.6】Plang高级编程语言(发布)
- 电子密码锁_毕设‘指导’
- [DS3231 RTC real-time clock module and Arduino interface to build a digital clock]
- Cadence allegro导出Gerber文件(制板文件)图文操作
- Lightly 支持 Markdown 文件在线编写(文中提供详细 Markdown 语法)
- IDEA2021.2安装与配置(持续更新)
- Process (in): process state, process address space
猜你喜欢
蛮力法求解凸包问题
改变文件的扩展名
GM7150,振芯科技,视频解码器,CVBS转BT656/601,QFN32,替换TVP5150/CJC5150
电子密码锁_毕设‘指导’
【详解】优先级队列的底层实现
【plang 1.4.5】编写坦克(双人)游戏脚本
2020 - AAAI - Image Inpainting论文导读《Learning to Incorporate Structure Knowledge for Image Inpainting》
Personal image bed construction based on Alibaba Cloud OSS+PicGo
电脑基本知识
单火线开关设计详解
随机推荐
同时求最大值与最小值(看似简单却值得思考~)
引擎开发日志:OpenGL资源多线程加载
R语言 —— 多元线性回归
Based on the raspberry pie smart luggage development environment set up
改变文件的扩展名
GM8284DD,GM8285C,GM8913,GM8914,GM8905C,GM8906C,国腾振芯LVDS类芯片
字符串匹配(蛮力法+KMP)
Lightly 支持 Markdown 文件在线编写(文中提供详细 Markdown 语法)
将ORCAD原理图导入allegro中进行PCB设计
【多线程】线程安全保护机制
TQP3M9009电路设计
78XX 79XX多路输出电源
[DS3231 RTC real-time clock module and Arduino interface to build a digital clock]
[Popular Science Post] I2C Communication Protocol Detailed Explanation - Partial Software Analysis and Logic Analyzer Example Analysis
MPU6050 accelerometer and gyroscope sensor is connected with the Arduino
LT9211芯片资料分享
uniCloud use
【LeetCode】链表相加 进位
Anaconda(Jupyter)里发现不能识别自己的GPU该怎么办?
PCB设计思路