当前位置:网站首页>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;
}
边栏推荐
猜你喜欢
设备管理中数据聚类处理
Uniapp编译后小程序的代码反编译一些思路
【Windows】你不能访问此共享文件夹,因为你组织的安全策略阻止未经身份验证的来宾访问,这些策略可帮助保护你的电脑
直播课堂系统09--腾讯云点播管理模块(一)
用示波器揭示以太网传输机制
JS中的filter、map、reduce
【vulhub】MySql身份认证绕过漏洞复现(CVE-2012-2122)
玩转doxygen 之RT-THREAD
直播课堂系统08-腾讯云对象存储和课程分类管理
npm warn config global `--global`, `--local` are deprecated. use `--location=global` instead.
随机推荐
wget编译升级故障解决
ENVI最小距离、最大似然、支持向量机遥感影像分类
LeetCode questions 1-10
睡前故事|用Bitmap与AST做一个配置化时长系统
The evolution history of Go programmers
优化是一种习惯●出发点是'站在靠近临界'的地方
第五届“强网杯”全国网络安全挑战赛(线上赛)
web逆向之丁香园
Knowledge map Knowledge Graph
C. Rotation Matching
kuberentes Auditing 入门
ctfshow-osint
Single-click to cancel the function
PostgreSQL — Installation and Common Commands
CGO Preliminary Cognition and Basic Data Type Conversion
[mysql] 深入分析MySQL版本控制MVCC规则
LeetCode-498-对角线遍历
饿了么-机构树单选
Getting started with kuberentes Auditing
变量和它的特性——《mysql 从入门到内卷再到入土》