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

leetcode——二叉树问题汇总

leetcode 144. 二叉树的前序遍历

 ①递归法:

/*** 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 {public void traversal(TreeNode cur, List<Integer> ans){if(cur == null) return;ans.add(cur.val);traversal(cur.left,ans);traversal(cur.right,ans);}public List<Integer> preorderTraversal(TreeNode root) {List<Integer> ans = new ArrayList<>();traversal(root,ans);return ans;}
}

②迭代法:

/*** 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 {public List<Integer> preorderTraversal(TreeNode root) {LinkedList<TreeNode> stack = new LinkedList<>();List<Integer> ans = new ArrayList<>();if(root == null) return ans;stack.push(root);while(stack.size() != 0){TreeNode node = stack.pop();ans.add(node.val);if(node.right != null) stack.push(node.right);if(node.left != null) stack.push(node.left);}return ans;}
}

        LinkedList可以用于模拟栈和队列, push和pop可以用于模拟栈,add()和remove()可以用于模拟队列。

leetcode 94. 二叉树的中序遍历

 

  ①递归法:

/*** 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 {public void traversal(TreeNode cur, List<Integer> ans){if(cur == null) return;traversal(cur.left,ans);ans.add(cur.val);traversal(cur.right,ans);}public List<Integer> inorderTraversal(TreeNode root) {List<Integer> ans = new ArrayList<>();traversal(root,ans);return ans;}
}

②迭代法: 

/*** 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 {public List<Integer> inorderTraversal(TreeNode root) {LinkedList<TreeNode> stack = new LinkedList<>();List<Integer> ans = new ArrayList<>();TreeNode cur = root;while(cur != null || stack.size() != 0){if(cur != null){stack.push(cur);cur = cur.left;//左}else{cur = stack.pop();ans.add(cur.val);//中cur = cur.right;//右}}return ans;}
}

leetcode 145. 二叉树的后序遍历

  ①递归法:

/*** 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 {public void traversal(TreeNode cur, List<Integer> ans){if(cur == null) return;traversal(cur.left,ans);traversal(cur.right,ans);ans.add(cur.val);}public List<Integer> postorderTraversal(TreeNode root) {List<Integer> ans = new ArrayList<>();traversal(root,ans);return ans;}
}

leetcode 102. 二叉树的层序遍历

队列迭代法:

/*** 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 {public List<List<Integer>> levelOrder(TreeNode root) {List<List<Integer>> ans = new ArrayList<>();LinkedList<TreeNode> queue = new LinkedList<>();if(root != null) queue.add(root);while(queue.size() != 0){int size = queue.size();List<Integer> list = new ArrayList<>();for(int i=0; i<size; i++){TreeNode node = queue.remove();list.add(node.val);if(node.left != null) queue.add(node.left);if(node.right != null) queue.add(node.right);}ans.add(list);}return ans;}
}

leetcode 226. 翻转二叉树

        在层序遍历的代码上添加交换左右节点的逻辑即可: 

/*** 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 {public TreeNode invertTree(TreeNode root) {LinkedList<TreeNode> queue = new LinkedList<>();if(root != null) queue.add(root);while(queue.size() != 0){int size = queue.size();for(int i=0; i<size; i++){TreeNode node = queue.pop();//交换左右孩子节点TreeNode temp = node.left;node.left = node.right;node.right = temp;if(node.left != null) queue.add(node.left);if(node.right != null) queue.add(node.right);}}return root;}
}

leetcode 101. 对称二叉树

/*** 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 {public boolean isSymmetric(TreeNode root) {LinkedList<TreeNode> queue = new LinkedList<>();queue.add(root.left);queue.add(root.right);while(queue.size() != 0){TreeNode leftNode = queue.remove();TreeNode rightNode = queue.remove();if(leftNode == null && rightNode == null) continue;if(leftNode == null || rightNode == null || leftNode.val != rightNode.val) return false;queue.add(leftNode.left);queue.add(rightNode.right);queue.add(leftNode.right);queue.add(rightNode.left);}return true;}
}

leetcode 104. 二叉树的最大深度

        本题在层序遍历的代码上修改即可,每一层代表深度+1:

/*** 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 {public int maxDepth(TreeNode root) {if(root == null) return 0;LinkedList<TreeNode> queue = new LinkedList<>();int ans = 0;queue.add(root);while(queue.size() != 0){int size = queue.size();ans++;for(int i=0; i<size; i++){TreeNode node = queue.remove();if(node.left != null) queue.add(node.left);if(node.right != null) queue.add(node.right);}}return ans;}
}

leetcode 111. 二叉树的最小深度

        大致思路和求二叉树最大深度类似,在内层while循环中加一句判断:当当前节点的左右节点都为空时,直接返回当前深度,此时也就是二叉树的最小深度。

/*** 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 {public int minDepth(TreeNode root) {if(root == null) return 0;int ans = 0;LinkedList<TreeNode> queue = new LinkedList<>();queue.add(root);while(queue.size() != 0){int size = queue.size();ans++;for(int i=0; i<size; i++){TreeNode node = queue.remove();if(node.left == null && node.right == null) return ans;if(node.left != null) queue.add(node.left);if(node.right != null) queue.add(node.right);}}return ans;}
}

leetcode 222. 完全二叉树的节点个数

        用层序遍历的逻辑做即可:

/*** 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 {public int countNodes(TreeNode root) {int ans = 0;if(root == null) return 0;LinkedList<TreeNode> queue = new LinkedList<>();queue.add(root);while(queue.size() != 0){int size = queue.size();for(int i=0; i<size; i++){ans++;TreeNode node = queue.remove();if(node.left != null) queue.add(node.left);if(node.right != null) queue.add(node.right);}}return ans;}
}

leetcode 96. 不同的二叉搜索树

         本题利用动态规划来做,分析当n=3的情况:

  • 当1作为根节点,此时左子树有0个节点,右子树有2两个节点,此时的二叉树种数应该有dp[0]*dp[2]种。
  • 当2作为根节点,此时左右子树各有一个节点,种数都是dp[1],此时的二叉树种数应该有dp[1]*dp[1]种。
  • 当3作为根节点,此时情况和第一种情况类似,只是左右子树交换了。
class Solution {public int numTrees(int n) {int[] dp = new int[n+1];dp[0] = 1;dp[1] = 1;for(int i=2; i<=n; i++){for(int j=0; j<i; j++){dp[i] += dp[j] * dp[i-j-1];}}return dp[n];}
}

相关文章:

leetcode——二叉树问题汇总

leetcode 144. 二叉树的前序遍历 ①递归法&#xff1a; /*** 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,…...

Android基础开发-饿汉式申请权限

1、案例&#xff0c;打开app时&#xff0c;就要申请权限 直接在onCreateView中申请所有权限就可&#xff0c;然后在选择的回调里边判断申请的结果 package com.example.client;import android.Manifest; import android.content.Intent; import android.content.pm.PackageMa…...

java Day7 正则表达式|异常

文章目录 1、正则表达式1.1 常用1.2 字符串匹配&#xff0c;提取&#xff0c;分割 2、异常2.1 运行时异常2.2 编译时异常2.3 自定义异常2.3.1 自定义编译时异常2.3.2 自定义运行时异常 1、正则表达式 就是由一些特定的字符组成&#xff0c;完成一个特定的规则 可以用来校验数据…...

Python算法题集_搜索二维矩阵

Python算法题集_搜索二维矩阵 题74&#xff1a;搜索二维矩阵1. 示例说明2. 题目解析- 题意分解- 优化思路- 测量工具 3. 代码展开1) 标准求解【矩阵展开为列表二分法】2) 改进版一【行*列区间二分法】3) 改进版二【第三方模块】 4. 最优算法5. 相关资源 本文为Python算法题集之…...

学习笔记:顺序表和链表(一、顺序表)

首先来个导言&#xff1a; 1.数组的优势&#xff1a;下标的随机访问&#xff0c;物理空间连续。数组指针用[ ]或者 * , 结构体指针用 - > 2.书写习惯 test.c写出主体框架 QelList.c写出结构体、头文件、函数声明 QelList.c写出函数的实现 3.挪动&#xff1a;如果从前…...

Midjourney从入门到实战:图像生成命令及参数详解

目录 0 专栏介绍1 Midjourney Bot常用命令2 Midjourney绘图指令格式3 Midjourney绘图指令参数3.1 模型及版本3.2 画面比例3.3 风格化3.4 图片质量3.5 混乱值3.6 随机数种子3.7 重复贴图3.8 停止3.8 垫图权重3.9 提示词权重分割 0 专栏介绍 &#x1f525;Midjourney是目前主流的…...

C语言分析基础排序算法——插入排序

目录 插入排序 直接插入排序 希尔排序 希尔排序基本思路解析 希尔排序优化思路解析 完整希尔排序文件 插入排序 直接插入排序 所谓直接插入排序&#xff0c;即每插入一个数据和之前的数据进行大小比较&#xff0c;如果较大放置在后面&#xff0c;较小放置在前面&#x…...

海格里斯HEGERLS智能托盘四向车系统为物流仓储自动化升级提供新答案

随着实体企业面临需求多样化、订单履行实时化、商业模式加速迭代等挑战&#xff0c;客户对物流仓储解决方案的需求也逐渐趋向于柔性化、智能化。作为近十年来发展起来的新型智能仓储设备&#xff0c;四向车系统正是弥补了先前托盘搬运领域柔性解决方案的空白。随着小车本体设计…...

SQLiteC/C++接口详细介绍-sqlite3类(一)

上一篇&#xff1a;SQLiteC/C接口简介 下一篇&#xff1a;SQLiteC/C接口详细介绍&#xff08;二&#xff09; 引言&#xff1a; SQLite C/C 数据库接口是一个流行的SQLite库使用形式&#xff0c;它允许开发者在C和C代码中嵌入 SQLite 基本功能的解决方案。通过 SQLite C/C 数据…...

基于UDP实现直播间聊天的功能

需求&#xff1a;软件划分为用户客户端和主播服务端两个软件client.c和server.c 用户客户端负责&#xff1a;1.接收用户的昵称2.接收用户输入的信息&#xff0c;能够将信息发送给服务端3.接收服务端回复的数据信息,并完成显示主播服务端负责&#xff1a;1.对所有加入直播间的用…...

html5cssjs代码 006 文章排版《桃花源记》

html5&css&js代码 006 文章排版《桃花源记》 一、代码二、解释页面整体结构&#xff1a;头部信息&#xff1a;CSS样式&#xff1a;文章内容&#xff1a; 这段代码定义了一个网页&#xff0c;用于展示文章《桃花源记》的内容。网页使用了CSS样式来定义各个部分的显示效果…...

勾八头歌之数据科学导论—数据采集实战

一、数据科学导论——数据采集基本概念 第1关&#xff1a;巧妇难为无米之炊 第2关&#xff1a;数据采集概念与内涵 二、数据科学导论——数据采集实战 第1关&#xff1a;单网页爬取 import urllib.request import csv import re# ********** Begin ********** # dataurllib.r…...

微信小程序云开发教程——墨刀原型工具入门(素材面板)

引言 作为一个小白&#xff0c;小北要怎么在短时间内快速学会微信小程序原型设计&#xff1f; “时间紧&#xff0c;任务重”&#xff0c;这意味着学习时必须把握微信小程序原型设计中的重点、难点&#xff0c;而非面面俱到。 要在短时间内理解、掌握一个工具的使用&#xf…...

C#与WPF通用类库

个人集成封装&#xff0c;仓库已公开 NetHelper 集成了一些常用的方法&#xff1b; 如通用的缓存静态操作类、常用的Wpf的ValueConverters、内置的委托类型、通用的反射加载dll操作类、Wpf的ViewModel、Command、Navigation、Messenger、部分常用UserControls(可绑定的Passwo…...

http协议中的强缓存与协商缓存,带图详解

此篇抽自本人之前的文章&#xff1a;http面试题整理 。 别急着跳转&#xff0c;先把缓存知识学会了~ http中的缓存分为两种&#xff1a;强缓存、协商缓存。 强缓存 响应头中的 status 是 200&#xff0c;相关字段有expires&#xff08;http1.0&#xff09;,cache-control&…...

蓝桥杯2019年第十届省赛真题-修改数组

查重类题目&#xff0c;想到用标记数组记录是否出现过 但是最坏情况下可能会从头找到小尾巴&#xff0c;时间复杂度O(n2)&#xff0c;数据范围106显然超时 再细看下题目&#xff0c;我们重复进行了寻找是否出现过&#xff0c;干脆把每个元素出现过的次数k记录下来&#xff0c;直…...

【Python使用】python高级进阶知识md总结第3篇:静态Web服务器-返回指定页面数据,静态Web服务器-多任务版【附代码文档】

python高级进阶全知识知识笔记总结完整教程&#xff08;附代码资料&#xff09;主要内容讲述&#xff1a;操作系统&#xff0c;虚拟机软件&#xff0c;Ubuntu操作系统&#xff0c;Linux内核及发行版&#xff0c;查看目录命令&#xff0c;切换目录命令&#xff0c;绝对路径和相对…...

ELK 日志分析系统

ELK &#xff08;Elasticsearch、Logstash、Kibana&#xff09;日志分析系统的好处是可以集中查看所有服务器日志&#xff0c;减轻了工作量&#xff0c;从安全性的角度来看&#xff0c;这种集中日志管理可以有效查询以及跟踪服务器被攻击的行为。 Elasticsearch 是个开源分布式…...

机器学习模型—逻辑回归

机器学习模型—逻辑回归 逻辑回归是一种用于分类任务的监督机器学习算法,其目标是预测实例属于给定类别的概率。逻辑回归是一种分析两个数据因素之间关系的统计算法。本文探讨了逻辑回归的基础知识、类型和实现。 什么是逻辑回归 逻辑回归用于二元分类,其中我们使用sigmoi…...

​Ubuntu20.04 创建新的用户​

1、了解Linux目录结构 推荐看一下&#xff1a;https://www.runoob.com/linux/linux-system-contents.html Linux支持多个用户进行操作的&#xff0c;这样提高了系统的安全性&#xff0c;也可以多人共用一个系统&#xff0c;不过要注意的是系统中安装的软件相关路径&#xff0…...

渗透实战PortSwigger靶场-XSS Lab 14:大多数标签和属性被阻止

<script>标签被拦截 我们需要把全部可用的 tag 和 event 进行暴力破解 XSS cheat sheet&#xff1a; https://portswigger.net/web-security/cross-site-scripting/cheat-sheet 通过爆破发现body可以用 再把全部 events 放进去爆破 这些 event 全部可用 <body onres…...

2.Vue编写一个app

1.src中重要的组成 1.1main.ts // 引入createApp用于创建应用 import { createApp } from "vue"; // 引用App根组件 import App from ./App.vue;createApp(App).mount(#app)1.2 App.vue 其中要写三种标签 <template> <!--html--> </template>…...

工业自动化时代的精准装配革新:迁移科技3D视觉系统如何重塑机器人定位装配

AI3D视觉的工业赋能者 迁移科技成立于2017年&#xff0c;作为行业领先的3D工业相机及视觉系统供应商&#xff0c;累计完成数亿元融资。其核心技术覆盖硬件设计、算法优化及软件集成&#xff0c;通过稳定、易用、高回报的AI3D视觉系统&#xff0c;为汽车、新能源、金属制造等行…...

Springboot社区养老保险系统小程序

一、前言 随着我国经济迅速发展&#xff0c;人们对手机的需求越来越大&#xff0c;各种手机软件也都在被广泛应用&#xff0c;但是对于手机进行数据信息管理&#xff0c;对于手机的各种软件也是备受用户的喜爱&#xff0c;社区养老保险系统小程序被用户普遍使用&#xff0c;为方…...

NXP S32K146 T-Box 携手 SD NAND(贴片式TF卡):驱动汽车智能革新的黄金组合

在汽车智能化的汹涌浪潮中&#xff0c;车辆不再仅仅是传统的交通工具&#xff0c;而是逐步演变为高度智能的移动终端。这一转变的核心支撑&#xff0c;来自于车内关键技术的深度融合与协同创新。车载远程信息处理盒&#xff08;T-Box&#xff09;方案&#xff1a;NXP S32K146 与…...

LangChain知识库管理后端接口:数据库操作详解—— 构建本地知识库系统的基础《二》

这段 Python 代码是一个完整的 知识库数据库操作模块&#xff0c;用于对本地知识库系统中的知识库进行增删改查&#xff08;CRUD&#xff09;操作。它基于 SQLAlchemy ORM 框架 和一个自定义的装饰器 with_session 实现数据库会话管理。 &#x1f4d8; 一、整体功能概述 该模块…...

4. TypeScript 类型推断与类型组合

一、类型推断 (一) 什么是类型推断 TypeScript 的类型推断会根据变量、函数返回值、对象和数组的赋值和使用方式&#xff0c;自动确定它们的类型。 这一特性减少了显式类型注解的需要&#xff0c;在保持类型安全的同时简化了代码。通过分析上下文和初始值&#xff0c;TypeSc…...

MySQL 部分重点知识篇

一、数据库对象 1. 主键 定义 &#xff1a;主键是用于唯一标识表中每一行记录的字段或字段组合。它具有唯一性和非空性特点。 作用 &#xff1a;确保数据的完整性&#xff0c;便于数据的查询和管理。 示例 &#xff1a;在学生信息表中&#xff0c;学号可以作为主键&#xff…...

Unity UGUI Button事件流程

场景结构 测试代码 public class TestBtn : MonoBehaviour {void Start(){var btn GetComponent<Button>();btn.onClick.AddListener(OnClick);}private void OnClick(){Debug.Log("666");}}当添加事件时 // 实例化一个ButtonClickedEvent的事件 [Formerl…...

Scrapy-Redis分布式爬虫架构的可扩展性与容错性增强:基于微服务与容器化的解决方案

在大数据时代&#xff0c;海量数据的采集与处理成为企业和研究机构获取信息的关键环节。Scrapy-Redis作为一种经典的分布式爬虫架构&#xff0c;在处理大规模数据抓取任务时展现出强大的能力。然而&#xff0c;随着业务规模的不断扩大和数据抓取需求的日益复杂&#xff0c;传统…...