当前位置:网站首页>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;
}
边栏推荐
猜你喜欢
随机推荐
npm warn config global `--global`, `--local` are deprecated. use `--location=global` instead.
Bedtime story | made a Bitmap and AST length system configuration
F. Binary String Reconstruction
PROCEDURE :存储过程结构——《mysql 从入门到内卷再到入土》
[Golang]如何优雅管理系统中的几十个UDF(API)
单选点击可取消功能
优化是一种习惯●出发点是'站在靠近临界'的地方
INSERT:插入操作语法&使用例——《mysql 从入门到内卷再到入土》
Future-oriented IT infrastructure management architecture - Unified IaaS
二级指针的简单理解
流程控制结构——《mysql 从入门到内卷再到入土》
参天生长大模型:昇腾AI如何强壮模型开发与创新之根?
机器学习笔记:t-SNE
Web3中值得关注的基础设施
【nvm】【node多版本管理工具】使用说明和踩坑(exit status 1)
PostgreSQL — Installation and Common Commands
A fullGC problem troubleshooting caused by groovy
(十二)STM32——NVIC中断优先级管理
C. Even Picture
一次由groovy引起的fullGC问题排查








