当前位置:网站首页>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;
}
边栏推荐
- 【go】依赖注入
- In 2021 China industrial Internet security competition (competition) in fujian province and the first industry of fujian province Internet innovation competition
- D. Game With Array
- 优化是一种习惯●出发点是'站在靠近临界'的地方
- 工程师应该怎么学习
- F. Binary String Reconstruction
- 2021DozerCTF
- ArcMap创建镶嵌数据集、导入栅格图像并修改像元数值显示范围
- win7开机有画面进系统黑屏怎么办
- B. Same Parity Summands
猜你喜欢
内置模板市场,DataEase开源数据可视化分析平台v1.13.0发布
机器学习笔记:t-SNE
论文解读(g-U-Nets)《Graph U-Nets》
npm warn config global `--global`, `--local` are deprecated. use `--location=global` instead.
.NET现代应用的产品设计 - DDD实践
着力提升制造业核心竞争力,仪器仪表产业迎高质量发展
【go】依赖注入
npm warn config global `--global`, `--local` are deprecated. use `--location=global` instead.
ansible各个模块的详解和使用
The use of TortoiseSVN little turtle
随机推荐
DDL:CREATE 创建数据库——《mysql 从入门到内卷再到入土》
PROCEDURE :存储过程结构——《mysql 从入门到内卷再到入土》
ACM解题笔记——HDU 1401 Solitaire(DBFS)
[mysql] 深入分析MySQL版本控制MVCC规则
函数:函数删除操作语法&使用例——《mysql 从入门到内卷再到入土》
找的笔试题的复盘(一)
单选点击可取消功能
《mysql 从入门到内卷再到入土》——Mysql基础 学习笔记目录
mysql服务器参数设置
HGAME 2022 Week2 writeup by pankas
Rider调试ASP.NET Core时报thread not gc-safe的解决方法
UPDATE:修改数据语法使用例——《mysql 从入门到内卷再到入土》
Kubernetes Notes / Getting Started / Production Environment / Installing Kubernetes with Deployment Tools / Starting a Cluster with kubeadm / Creating a Cluster with kubeadm
Single-click to cancel the function
ACM模板笔记:八数码问题——使用BFS+康托展开打表解决
PostgreSQL 介绍
优化是一种习惯●出发点是'站在靠近临界'的地方
2021 CybricsCTF
测试代码新的规则
将视图模型转换为使用 Hilt 依赖注入