当前位置:网站首页>LeetCode-36-Binary search tree and doubly linked list
LeetCode-36-Binary search tree and doubly linked list
2022-08-10 21:26:00 【z754916067】
题目
思路
- Read the topic for a long time…The meaning should be that there is a complete binary search tree,Arranged in a doubly linked list from smallest to largest.
- It is obvious that an inorder traversal of this binary search tree can form a sorted sequence,Then build a doubly linked list.
代码
ArrayList<Integer> AL = new ArrayList<>();
public Node treeToDoublyList(Node root) {
if(root==null) return null;
//First traverse this in-orderroot Find the sorted array
DFS(root);
//将arrayslistThe numbers are constructed as a doubly linked list
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;
//head and tail node records
Node head = null;
Node tail = null;
//It takes two rounds
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){
//只有一个元素 Its beginning and end are itself
tail.left = tail;
tail.right = tail;
return tail;
}
//开始连接head和tail And build a linked list in the other direction
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;
}
边栏推荐
- C. Even Picture
- mysql服务器参数设置
- 【Windows】你不能访问此共享文件夹,因为你组织的安全策略阻止未经身份验证的来宾访问,这些策略可帮助保护你的电脑
- Future与CompletableFuture
- ENVI自动生成地面控制点实现栅格影像的自动地理配准
- 【ACM】dp专场训练
- Bedtime story | made a Bitmap and AST length system configuration
- Object.assign用法 以及 与$.extend的区别
- npm warn config global `--global`, `--local` are deprecated. use `--location=global` instead.
- 函数:函数删除操作语法&使用例——《mysql 从入门到内卷再到入土》
猜你喜欢
随机推荐
查询:复杂查询的语法和使用例——《mysql 从入门到内卷再到入土》
[Golang]如何优雅管理系统中的几十个UDF(API)
机器学习笔记:t-SNE
微擎盲盒交友变现-vp_ph打开慢优化
Bedtime story | made a Bitmap and AST length system configuration
玩转doxygen 之RT-THREAD
apr_thread使用内存之谜
The evolution history of Go programmers
【go】依赖注入
Go程序员进化史
如何提高代码的可读性 学习笔记
C. Social Distance
Date picker component (restrict year to set only displayed months)
ctfshow-osint
设备管理中数据聚类处理
用示波器揭示以太网传输机制
美创科技勒索病毒“零信任”防护和数据安全治理体系的探索实践
Before implementing MES management system, these three questions to consider
【实用软件】【VSCode】使用技巧大全(持续更新)
Redis 性能影响 - 异步机制和响应延迟