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

leetcode226-翻转二叉树

leetcode 226
在这里插入图片描述

思路

翻转二叉树就是交换每个元素的左右节点,首先在root层交换左右节点,然后再到子树交换左右节点

方法1 层序遍历

var invertTree = function (root) {
    if (!root) return root;
    const queue = [root], result = [];
    while(queue.length){
        let len = queue.length;
        while(len--){
            const node = queue.shift();
            // 交换左右节点
            const temp = node.left;
            node.left = node.right;
            node.right = temp;
            node.left && queue.push(node.left)
            node.right && queue.push(node.right)
        }
    }
    return root;
};

方法2 前序遍历递归法

var invertTree = function (root) {
    const deep = (root) => {
        if (!root) return;
        const temp = root.left;
        root.left = root.right;
        root.right = temp;
        deep(root.left)
        deep(root.right)
    }
    deep(root)
    return root;
};

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

相关文章:

  • 高并发微服务日志管理:ELK、Loki、Fluentd 终极对决与实战指南
  • MySql:Authentication plugin ‘caching sha2 password‘ cannot be loaded
  • PHP Zip 文件处理指南
  • 父组件用的是原生监听,子组件用的是onClick,子组件添加了stopPropagation还是没有阻止传播
  • LeetCode 解题思路 2(Hot 100)
  • R-INLA实现绿地与狐狸寄生虫数据空间建模:含BYM、SPDE模型及PC先验应用可视化...
  • ai大模型自动化测试-TensorFlow Testing 测试模型实例
  • python实战项目58:采集蜻蜓FM热门音频top排行榜
  • 基于MATLAB的OFDM通信系统仿真设计
  • ESP32移植Openharmony外设篇(8)MQ-3酒精检测传感器
  • 鸿蒙Next-方法装饰器以及防抖方法注解实现
  • 【Redis 原理】网络模型
  • 社群团购平台的愿景构建与开源链动2+1模式S2B2C商城小程序应用探索
  • vscode多文件编译构建(CMake)和调试C++
  • 系统思考:第五项修炼
  • Transceivers Wizard IP核
  • zookeeper 客户端常用命令
  • 8. 示例:对32位数据总线实现位宽和值域覆盖
  • 5. grafana的Graph panel使用
  • C 语言中控制文件的读取或写入光标