当前位置:网站首页>LeetCode-36-二叉搜索树与双向链表
LeetCode-36-二叉搜索树与双向链表
2022-08-10 20:54:00 【z754916067】
题目
思路
- 看题目看了半天…意思应该是有一个完整的二叉搜索树,按从小到大排成双向链表。
- 很明显中序遍历这个二叉搜索树能构成一个已排序的序列,然后构建双向链表即可。
代码
ArrayList<Integer> AL = new ArrayList<>();
public Node treeToDoublyList(Node root) {
if(root==null) return null;
//首先中序遍历这个root 找到排序后的数组
DFS(root);
//将arrayslist里的数构建成双向链表
return createLink(AL);
}
public void DFS(Node root){
if(root==null) return;
DFS(root.left);
AL.add(root.val);
DFS(root.right);
}
public Node createLink(ArrayList a){
//pre和next记录
Node pre = null;
Node next = null;
//首尾节点记录
Node head = null;
Node tail = null;
//必须得两轮才可以
for(int i=a.size()-1;i>=0;i--){
Node temp = new Node((Integer) a.get(i));
if(i==a.size()-1){
tail = temp; // 记录
next = tail;
}
if(i!=a.size()-1){
temp.right=next;
next = temp;
if(i==0) head=temp;
}
}
if(head==null){
//只有一个元素 其首尾都是自己
tail.left = tail;
tail.right = tail;
return tail;
}
//开始连接head和tail 并且构建另一个方向的链表
tail.right = head;
head.left=tail;
//从2开始构建
Node temp = head.right;
pre = head;
while (tail.left==null){
temp.left = pre;
temp = temp.right;
pre = pre.right;
}
return head;
}
边栏推荐
- Kubernetes Notes / Getting Started / Production Environment / Installing Kubernetes with Deployment Tools / Starting a Cluster with kubeadm / Creating a Cluster with kubeadm
- 论文解读(g-U-Nets)《Graph U-Nets》
- 基于Pix4Dmapper的运动结构恢复法无人机影像三维模型重建
- How to submit a PR?【OpenHarmony Growth Plan】【OpenHarmony Open Source Community】
- 图扑智慧电力可视化大屏,赋能虚拟电厂精准减碳
- B. Codeforces Subsequences
- 【nvm】【node多版本管理工具】使用说明和踩坑(exit status 1)
- 扩展中国剩余定理
- The use of TortoiseSVN little turtle
- 第四届红帽杯网络安全大赛
猜你喜欢
TCL:事务的特点,语法,测试例——《mysql 从入门到内卷再到入土》
社区分享|货拉拉通过JumpServer纳管大规模云上资产
化学制品制造业数智化供应链管理系统:建立端到端供应链采购一体化平台
Future与CompletableFuture
面向未来的 IT 基础设施管理架构——融合云(Unified IaaS)
机器学习笔记:t-SNE
【go】依赖注入
Future-oriented IT infrastructure management architecture - Unified IaaS
壁仞推出全球最大算力芯片,号称以7nm超越英伟达4nm最新GPU
OPPO Enco X2 迎来秋季产品升级 旗舰体验全面拉满
随机推荐
图扑智慧电力可视化大屏,赋能虚拟电厂精准减碳
Getting started with kuberentes Auditing
svg+元素js实现在图片上描点成框,并获取相对图片的坐标位置
第五届“强网杯”全国网络安全挑战赛(线上赛)
ENVI最小距离、最大似然、支持向量机遥感影像分类
【CMU博士论文】视频多模态学习:探索模型和任务复杂性,152页pdf
A fullGC problem troubleshooting caused by groovy
【一致性hash】负载均衡器分发请求
Detailed explanation of the use of Oracle's windowing function (2)
.NET现代应用的产品设计 - DDD实践
Uniapp编译后小程序的代码反编译一些思路
PostgreSQL — 安装及常用命令
Rider调试ASP.NET Core时报thread not gc-safe的解决方法
通用线程:POSIX 线程详解,第 2部分
扩展中国剩余定理
npm warn config global `--global`, `--local` are deprecated. use `--location=global` instead.
【nvm】【node多版本管理工具】使用说明和踩坑(exit status 1)
Web3中值得关注的基础设施
[mysql] 深入分析MySQL版本控制MVCC规则
OPPO Enco X2 迎来秋季产品升级 旗舰体验全面拉满