LCR 155. 将二叉搜索树转化为排序的双向链表

news/2024/7/24 4:29:39 标签: 链表, 数据结构, 经验分享, 算法, 笔记

力扣链接icon-default.png?t=N7T8https://leetcode.cn/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof/description/

解题思路

中序遍历可以得到排序的序列,遍历时维护当前节点和前一个节点,改变左右指针。头节点设为null,遍历开始判断一下然后初始化。尾节点中序遍历时一直更新。

/*
// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val,Node _left,Node _right) {
        val = _val;
        left = _left;
        right = _right;
    }
};
*/

class Solution {
    Node head,end;
    void dfs(Node root){
        if(root==null){
            return;
        }
        dfs(root.left);
        if(head==null){
            head=root;
        }
        else{
            root.left=end;
            end.right=root;
        }
        end=root;        //作为前继节点
        dfs(root.right);
    }
    public Node treeToDoublyList(Node root) {
        if(root==null){
            return null;
        }
        dfs(root);
        head.left=end;
        end.right=head;
        return head;
    }
}


http://www.niftyadmin.cn/n/5546921.html

相关文章

虚拟内存【Linux】

虚拟内存 为什么需要虚拟内存Linux虚拟内存的结构32位系统下的虚拟地址空间64位系统下的虚拟地址空间页表多级页表TLB 流程虚拟内存的作用 为什么需要虚拟内存 为了在进行多进程编码进行内存访问的时候保持内存的隔离性,数据安全性,所以出现了虚拟内存。…

Linux系统(CentOS)安装Mysql5.7.x

安装准备: Linux系统(CentOS)添加防火墙、iptables的安装和配置 请访问地址:https://blog.csdn.net/esqabc/article/details/140209894 1,下载mysql安装文件(mysql-5.7.44为例) 选择Linux通用版本64位(L…

vue项目本地开启https协议访问(vite)

官网介绍:vite官方文档 1、根据官方文档安装依赖vitejs/plugin-basic-ssl npm install -D vitejs/plugin-basic-ssl2、在vite.config.js或者vite.config.ts中配置:server中的https和plugins import { defineConfig } from "vite"; import b…

大数据------JavaWeb------FilterListenerAJAXAxiosJSON

Filter Filter简介 定义:Filter表示过滤器,是JavaWeb三大组件(Servlet、Filter、Listener)之一。 作用:它可把对资源(Servlet、JSP、Html)的请求拦截下来从而实现一些特殊功能 过滤器一般完成…

构造函数注入@RequiredArgsConstructor

Api(tags "用户管理接口") RequiredArgsConstructor RestController RequestMapping("users") public class UserController {private final IUserService userService;PostMappingApiOperation("新增用户")public void saveUser(RequestBody U…

电脑必备下载神器 - Internet Download Manager (IDM) 6如何终身版使用

— 下载神器 — Internet Download Manager (IDM) 需要经常在网页上下载文件,下载速度慢怎么办?Internet Download Manager (IDM) 来帮忙,帮你打开加速模式,下载速度提升至5倍,多线程满速下载,跑至宽带上限…

探索C嘎嘎的奇妙世界:第十九关---STL(list的模拟实现)

1. 基本框架 首先&#xff0c;我们先从节点的准备工作入手&#xff0c;请看示例&#xff1a; #pragma once #include<iostream> #include<assert.h> using namespace std; //节点 template<class T> struct ListNode {ListNode<T>* _next;Li…

RedHat运维-Linux存储管理基础2-管理交换分区

1. 在/dev/sdb这块磁盘中&#xff0c;已知已有两个分区&#xff0c;并且第二个分区在42MB处结尾。现在新创建一个大小为2G的分区&#xff0c;并将其格式化为交换分区&#xff0c;方法是__________________________&#xff1b; 2. 在/dev/nvme0n2这块磁盘中&#xff0c;已知已有…