当前位置: 首页 > article >正文

力扣.623. 在二叉树中增加一行(链式结构的插入操作)

Problem: 623. 在二叉树中增加一行

文章目录

  • 题目描述
  • 思路
  • 复杂度
  • Code

题目描述

在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述

思路

1.首先要说明,对于数据结构无非两大类结构:顺序结构链式结构,而二叉树实质上就可以等效看作为一个二叉链表,而对于链表插入一个节点的操作是应较为熟练掌握的所以二叉树的插入节点操作其实是相类似的操作,同时由于二叉树的特性,我们无法像遍历单链表那样对于二叉树进行迭代遍历操作,而为了实现在二叉树中插入节点,我们有需要利用递归操作完成,具体到本题
2.对于层数为1时,做特殊处理,直接将待插入的节点作为根节点,原始的二叉树作为其左子树
3.对于一般情况,我们做二叉树的先序遍历当递归到的层数为给定层数减一时进行插入操作即可

复杂度

时间复杂度:

O ( n ) O(n) O(n);其中 n n n为二叉树的节点个数

空间复杂度:

O ( h ) O(h) O(h);其中 h h h为二叉树的高度

Code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private int targetVal;
    private int targetDepth;
    private int curDepth = 0;

    public TreeNode addOneRow(TreeNode root, int val, int depth) {
        targetDepth = depth;
        targetVal = val;
        // Insert into the first line with special treatment
        if (targetDepth == 1) {
            TreeNode newRoot = new TreeNode(val);
            newRoot.left = root;
            return newRoot;
        }  
        // Walk through the binary tree and insert the corresponding row
        traverse(root);
        return root;
    }

    private void traverse(TreeNode root) {
        if (root == null) {
            return;
        }
        curDepth++;
        if (curDepth == targetDepth - 1) {
            TreeNode newLeftNode = new TreeNode(targetVal);
            TreeNode newRightNode = new TreeNode(targetVal);
            newLeftNode.left = root.left;
            newRightNode.right = root.right;
            root.left = newLeftNode;
            root.right = newRightNode;
        }
        traverse(root.left);
        traverse(root.right);
        curDepth--;
    }
}


http://www.kler.cn/a/536636.html

相关文章:

  • 6 maven工具的使用、maven项目中使用日志
  • docker数据持久化的意义
  • Linux TCP 编程详解与实例
  • 判断您的Mac当前使用的是Zsh还是Bash:echo $SHELL、echo $0
  • DKG(Distributed Key Generation)协议
  • Google地图瓦片爬虫——进阶版
  • LeetCode--279. 完全平方数【动态规划】
  • 深度学习模型格式解析:PyTorch、AWQ 和 GPTQ
  • @RequestBody与@ResponseBody:Spring数据处理的“翻译官”
  • 基于PSO粒子群优化和Voronoi图的配电网电动汽车充电站最优选址matlab仿真
  • error: externally-managed-environment
  • 【网络安全学习笔记】传输层协议 UDP 与 TCP
  • 【物联网IoT - 10分钟,构建一个自己的MQTT Broker服务!】
  • 第17章 读写锁分离设计模式(Java高并发编程详解:多线程与系统设计)
  • 基于Flask的历史空难数据可视化分析系统的设计与实现
  • [ESP32:Vscode+PlatformIO]添加第三方库 开源库 与Arduino导入第三方库的区别
  • MWORKS 2025a | 模型降阶与融合仿真工具聚焦用户体验全面升级
  • stable diffusion安装包与常用模型下载
  • spy-debugger + Charles 调试移动端/内嵌小程序H5
  • CSS盒子模型详解
  • Three.js实现一个动态的 3D 点阵波浪效果
  • 保姆级教程 !SQL Server数据库的备份和还原
  • 语言模型测试系列【12】
  • web-RCE-CTFHub
  • 蓝桥杯Java之输入输出练习题
  • 深入了解回调函数(Callback Function)