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

数据结构与算法之二叉树: LeetCode 226. 翻转二叉树 (Typescript版)

翻转二叉树

  • https://leetcode.cn/problems/invert-binary-tree/

描述

  • 给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。

示例 1

       4                                4
    /     \                          /     \
   2       7          ===>          7       2
  / \     / \                      / \     / \
 1   3   6   9                    9   6   3   1
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]

示例 2

       2                                2
    /     \          ===>            /     \
   1       3                        3       1
输入:root = [2,1,3]
输出:[2,3,1]

示例 3

输入:root = []
输出:[]

提示

  • 树中节点数目范围在 [0, 100] 内
  • -100 <= Node.val <= 100

算法实现

1 )深度优先递归版本

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function invertTree(root: TreeNode | null): TreeNode | null {
    // 如果是叶子节点,没有左右子树,这里为null, 则停止
    if(!root) return null;
    // 将翻转树返回
    return {
        val: root.val,
        left: invertTree(root.right),
        right: invertTree(root.left)
    }
}
  • 解题思路
    • 先翻转左右子树,再将子树换个位置
    • 符合:分、解、合 特性
  • 解题步骤
    • 分:获取左右子树
    • 解:递归地翻转左右子树
    • 合:将翻转后的左右子树换个位置放到根节点
  • 时间复杂度:O(n)
  • 空间复杂度:需要存放 O(h) 个函数调用(h是树的高度),所以是 O(h)

2 )广度优先迭代实现

function invertTree(root: TreeNode | null): TreeNode | null {
    if (!root) return null;
    const queue: (TreeNode | null)[] = [root]; // 队列
    while(queue.length) {
        const qTop = queue.shift(); // 取出队首
        [qTop.left, qTop.right] = [qTop.right, qTop.left]; // 交换左右节点 (关键)
        if (qTop.left) queue.push(qTop.left); // 左孩子入队
        if (qTop.right) queue.push(qTop.right); // 右孩子入队
    }
    return root;
}
  • 使用广度优先遍历处理
  • 时间复杂度:O(n)
  • 空间复杂度:O(n)

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

相关文章:

  • C++,STL 命名空间:理解 std 的作用、规范与陷阱
  • FFmpeg(7.1版本)编译:Ubuntu18.04交叉编译到ARM
  • 表格结构标签
  • 【huawei】云计算的备份和容灾
  • 一文了解性能优化的方法
  • ESP32-CAM实验集(WebServer)
  • 24. 深度学习进阶 - 矩阵运算的维度和激活函数
  • C#,《小白学程序》第十一课:双向链表(Linked-List)其二,链表的插入与删除的方法(函数)与代码
  • CocosCreator 面试题(十五)Cocos Creator如何内置protobuf JS版本?
  • Spring Boot 3.2.0 现已推出
  • 基于springboot实现私人健身与教练预约管理系统项目【项目源码+论文说明】计算机毕业设计
  • postgresql从入门到精通 - 第35讲:中间件PgBouncer部署|PostgreSQL教程
  • Re54:读论文 How Context Affects Language Models‘ Factual Predictions
  • 梯度详解与优化实战
  • Android 一键屏锁的实现
  • RabbitMQ之发送者(生产者)可靠性
  • Linux常用命令——bg命令
  • MyBatis的功能架构,MyBatis的框架架构设计,Mybatis都有哪些Executor执行器,Mybatis中如何指定使用哪一种Executor执行器
  • ctfshow刷题web入门--1--ljcsd
  • 【版本管理 | Git】Git rebase 命令最佳实践!确定不来看看?
  • P14 C++局部静态变量static延长生命周期
  • ubuntu下配置qtcreator交叉编译环境
  • 企业编码生成程序Python毕业设计
  • js中判断一个变量是数组的方式有哪些
  • [DFS深度优先搜索]集合里的乘法
  • 如何使用nginx部署静态资源