二叉树专项训练LeetCode

news/2024/5/18 22:06:28/文章来源:https://blog.csdn.net/weixin_46047677/article/details/127221374

144. 二叉树的前序遍历
image-20221005110955366

二叉树入门 递归 与 迭代

class Solution {List<Integer> ans = new ArrayList<>();void dfs(TreeNode root){if(root == null) {return;}ans.add(root.val);dfs(root.left);dfs(root.right);}public List<Integer> preorderTraversal(TreeNode root) {dfs(root);return ans;}//迭代public List<Integer> preorderTraversal2(TreeNode root) {List<Integer> list = new ArrayList<>();if (root == null) {return list;}Stack<TreeNode> stack = new Stack<>();stack.push(root);while (!stack.isEmpty()) {TreeNode node = stack.pop();list.add(node.val);if (node.right != null) {stack.add(node.right);}if(node.left != null){stack.add(node.left);}}return list;}}

145. 二叉树的后序遍历

image-20221005111219595

class Solution {List<Integer> ans = new ArrayList<>();void dfs(TreeNode root){if(root == null) {return;}dfs(root.left);dfs(root.right);ans.add(root.val);}public List<Integer> postorderTraversal(TreeNode root) {dfs(root);return ans;}//迭代 左右子换顺序进入栈 最后再反转list即为后序public List<Integer> postorderTraversal2(TreeNode root) {List<Integer> list = new ArrayList<>();if (root == null) {return list;}Stack<TreeNode> stack = new Stack<>();stack.push(root);while (!stack.isEmpty()) {TreeNode node = stack.pop();list.add(node.val);if(node.left != null){stack.add(node.left);}if (node.right != null) {stack.add(node.right);}}Collections.reverse(list);return list;}}

94. 二叉树的中序遍历
image-20221005111442987

class Solution {List<Integer> ans = new ArrayList<>();void dfs(TreeNode root){if(root == null) {return;}dfs(root.left);ans.add(root.val);dfs(root.right);}public List<Integer> inorderTraversal(TreeNode root) {dfs(root);return ans;}//迭代public List<Integer> inorderTraversal2(TreeNode root) {List<Integer> list = new ArrayList<>();if (root == null) {return list;}Stack<TreeNode> stack = new Stack<>();TreeNode x = root;while (x != null || !stack.isEmpty()) {if (x != null) {stack.push(x);x = x.left;}else{x = stack.pop();list.add(x.val);x = x.right;}}return list;}//能进行统一迭代法 只需改变压栈的顺序即可实现 前中后序遍历 这里只演示中序public List<Integer> inorderTraversal3(TreeNode root) {List<Integer> list = new ArrayList<>();if (root == null) {return list;}Stack<TreeNode> stack = new Stack<>();stack.push(root);while (!stack.isEmpty()) {TreeNode now = stack.peek();if (now != null) {TreeNode x = stack.pop();if (x.right != null) {stack.add(x.right);}stack.add(x);stack.add(null);if (x.left != null) {stack.add(x.left);}} else {stack.pop();TreeNode x = stack.pop();list.add(x.val);}}return list;}}

102. 二叉树的层序遍历

image-20221006085336228

class Solution {public List<List<Integer>> levelOrder(TreeNode root) {List<List<Integer>> ans = new ArrayList<>();Queue<TreeNode> queue = new ArrayDeque<>();if(root == null){return new ArrayList<>();}queue.add(root);while (!queue.isEmpty()) {int size = queue.size();List<Integer> list = new ArrayList<>();//不能 i < queue.size  因为queue长度再不断变化 每一个for循环就是一层for (int i = 0; i < size; i++) {TreeNode now = queue.poll();list.add(now.val);if (now.left != null) {queue.add(now.left);}if (now.right != null) {queue.add(now.right);}}ans.add(list);}return ans;}}

107. 二叉树的层序遍历 II

image-20221006090548598

只需要改变插入List的顺序即可 头插入

class Solution {public List<List<Integer>> levelOrderBottom(TreeNode root) {List<List<Integer>> ans = new Stack<>();Queue<TreeNode> queue = new ArrayDeque<>();if(root == null){return new ArrayList<>();}queue.add(root);while (!queue.isEmpty()) {int size = queue.size();List<Integer> list = new ArrayList<>();//不能 i < queue.size  因为queue长度再不断变化 每一个for循环就是一层for (int i = 0; i < size; i++) {TreeNode now = queue.poll();list.add(now.val);if (now.left != null) {queue.add(now.left);}if (now.right != null) {queue.add(now.right);}}ans.add(0,list);}return ans;}}

199. 二叉树的右视图

image-20221006091941477

class Solution {List<Integer> list = new ArrayList<>();void dfs(TreeNode x, int deep) {if (x != null) {if (deep == list.size()) {list.add(x.val);}dfs(x.right, deep + 1);dfs(x.left, deep + 1);}}public List<Integer> rightSideView(TreeNode root) {dfs(root, 0);return list;}}

637. 二叉树的层平均值

int 不够

class Solution {public List<Double> averageOfLevels(TreeNode root) {List<Double> ans = new ArrayList<>();Queue<TreeNode> queue = new ArrayDeque<>();queue.add(root);while(!queue.isEmpty()){int size = queue.size();long sum = 0;for(int i = 0 ; i < size;i++){TreeNode now = queue.poll();sum += now.val;if(now.left!=null) {queue.add(now.left);}if(now.right!=null){queue.add(now.right);}}ans.add(sum*1.0/size);}return ans;}}

429. N 叉树的层序遍历

image-20221006111349883

class Solution {public List<List<Integer>> levelOrder(Node root) {List<List<Integer>> ans = new ArrayList<>();Queue<Node> queue = new ArrayDeque<>();if(root == null){return new ArrayList<>();}queue.add(root);while(!queue.isEmpty()){int size = queue.size();List<Integer> now = new ArrayList<>();for(int i = 0 ; i < size;i++){Node x = queue.poll();now.add(x.val);for(int j = 0 ; j < x.children.size();j++){queue.add(x.children.get(j));}}ans.add(now);}return ans;}}

515. 在每个树行中找最大值

image-20221006111835098

class Solution {public List<Integer> largestValues(TreeNode root) {List<Integer> ans = new ArrayList<>();Queue<TreeNode> queue = new ArrayDeque<>();if (root == null) {return new ArrayList<>();}queue.add(root);while (!queue.isEmpty()) {int size = queue.size();int Max = Integer.MIN_VALUE;for (int i = 0; i < size; i++) {TreeNode now = queue.poll();Max = Math.max(Max,now.val);if (now.left != null) {queue.add(now.left);}if (now.right != null) {queue.add(now.right);}}ans.add(Max);}return ans;}}

429. N 叉树的层序遍历

class Solution {public List<List<Integer>> levelOrder(Node root) {List<List<Integer>> ans = new ArrayList<>();Queue<Node> queue = new ArrayDeque<>();if(root == null){return new ArrayList<>();}queue.add(root);while(!queue.isEmpty()){int size = queue.size();List<Integer> now = new ArrayList<>();for(int i = 0 ; i < size;i++){Node x = queue.poll();now.add(x.val);for(int j = 0 ; j < x.children.size();j++){queue.add(x.children.get(j));}}ans.add(now);}return ans;}}

104. 二叉树的最大深度

image-20221006140035362

递归找

class Solution {int dep = 0;void find(TreeNode x, int deep) {if (x == null) {return;}dep = Math.max(dep, deep);find(x.left, deep + 1);find(x.right, deep + 1);}public int maxDepth(TreeNode root) {find(root,1);return dep;}}

111. 二叉树的最小深度

image-20221006140454170

class Solution {int dep = Integer.MAX_VALUE;void find(TreeNode x, int deep) {if (x == null) {return;}if (x.left == null && x.right == null) {dep = Math.min(dep, deep);}find(x.left, deep + 1);find(x.right, deep + 1);}public int minDepth(TreeNode root) {if(root == null){return 0;}find(root,1);return dep;}}

226. 翻转二叉树

image-20221007084320236

class Solution {public TreeNode invertTree(TreeNode root) {if (root == null) {return null;}TreeNode tmp = root.left == null ? null : root.left;root.left = root.right == null ? null : root.right;root.right = tmp;if (root.right != null) {invertTree(root.right);}if (root.left != null) {invertTree(root.left);}return root;}public TreeNode invertTree2(TreeNode root) {if (root == null) {return null;}Queue<TreeNode> queue = new ArrayDeque<>();queue.add(root);while (!queue.isEmpty()) {int size = queue.size();for (int i = 0; i < size; i++) {TreeNode now = queue.poll();TreeNode temp = now.left;now.left = now.right;now.right = temp;if (now.left != null) {queue.offer(now.left);}if (now.right != null) {queue.offer(now.right);}}}return root;}}

101. 对称二叉树

class Solution {public boolean isSymmetric(TreeNode root) {if(root==null) {return true;}return dfs(root.left,root.right);}boolean dfs(TreeNode left, TreeNode right) {if(left==null && right==null) {return true;}if(left==null || right==null) {return false;}if(left.val!=right.val) {return false;}return dfs(left.left,right.right) && dfs(left.right,right.left);}}

104. 二叉树的最大深度

image-20221007085026183

class Solution {int dep = 0;void find(TreeNode x, int deep) {if (x == null) {return;}dep = Math.max(dep, deep);find(x.left, deep + 1);find(x.right, deep + 1);}public int maxDepth(TreeNode root) {find(root,1);return dep;}}

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

image-20221007085539956

class Solution {int ans = 0;void sum(TreeNode root){if(root == null) {return;}ans++;sum(root.left);sum(root.right);}public int countNodes(TreeNode root) {sum(root);return ans;}}

110. 平衡二叉树

image-20221007085929348

class Solution {public boolean isBalanced(TreeNode root) {if (root == null) {return true;} else {return Math.abs(height(root.left) - height(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);}}public int height(TreeNode root) {if (root == null) {return 0;} else {return Math.max(height(root.left), height(root.right)) + 1;}}}

257. 二叉树的所有路径

image-20221007091503797

class Solution {List<Integer> path = new ArrayList<>();List<String> ans = new ArrayList<>();void search(TreeNode root) {path.add(root.val);if (root.left == null && root.right == null) {StringBuffer sb = new StringBuffer();for (int i = 0; i < path.size(); i++) {if (i != 0) {sb.append("->");}sb.append(path.get(i));}ans.add(sb.toString());return;}if(root.left != null){search(root.left);path.remove(path.size()-1);}if(root.right != null){search(root.right);path.remove(path.size()-1);}}public List<String> binaryTreePaths(TreeNode root) {if(root == null){return new ArrayList<>();}search(root);return ans;}}

404. 左叶子之和

image-20221008094859514

class Solution {public int sumOfLeftLeaves(TreeNode root) {Queue<TreeNode> queue = new ArrayDeque<>();if (root == null) {return 0;}queue.offer(root);int sum = 0;while (!queue.isEmpty()) {TreeNode now = queue.poll();if (now.left != null) {if(now.left.left==null && now.left.right==null){sum+=now.left.val;}queue.add(now.left);}if(now.right!=null){queue.add(now.right);}}return sum;}}

513. 找树左下角的值

image-20221008095949206

class Solution {int dep = 0;int ans = -1;void dfs(TreeNode x , int deep){if(x == null){return;}if(x.left == null && x.right == null){if(deep > dep){dep = deep;ans = x.val;}}dfs(x.left,deep+1);dfs(x.right,deep+1);}public int findBottomLeftValue(TreeNode root) {dfs(root,1);return ans;}}

112. 路径总和

image-20221008101116367

class Solution {boolean ans = false;void dfs(TreeNode x, int target, int now) {if (x == null) {return;}if (x.left == null && x.right == null) {if (now+x.val == target) {ans = true;}}if (x.left != null) {dfs(x.left, target, now + x.val);}if (x.right != null) {dfs(x.right, target, now + x.val);}}public boolean hasPathSum(TreeNode root, int targetSum) {if(root == null){return false;}dfs(root, targetSum,0);return ans;}}

106. 从中序与后序遍历序列构造二叉树

image-20221008103335422

class Solution {Map<Integer, Integer> map;TreeNode dfs(int[] inorder, int l1, int r1, int[] postorder, int l2, int r2) {if(l1 >= r1 || l2 >= r2){return null;}int index = map.get(postorder[r2 -1]);TreeNode root = new TreeNode(inorder[index]);int len = index - l1;root.left = dfs(inorder,l1,index,postorder,l2,l2+len);root.right= dfs(inorder,index+1,r1,postorder,l2+len,r2-1);return root;}public TreeNode buildTree(int[] inorder, int[] postorder) {map = new HashMap<>();for (int i = 0; i < inorder.length; i++) {map.put(inorder[i], i);}return dfs(inorder, 0, inorder.length, postorder, 0, postorder.length);}}

105. 从前序与中序遍历序列构造二叉树
image-20221008104045804

class Solution {Map<Integer, Integer> map;TreeNode dfs(int[] preorder, int l1, int r1, int[] inorder, int l2, int r2) {if(l1 >= r1 || l2 >= r2){return null;}int index = map.get(preorder[l1]);TreeNode root = new TreeNode(inorder[index]);int len = index - l2;root.left = dfs(preorder,l1+1,l1+len+1,inorder,l2,index);root.right= dfs(preorder,l1+len+1,r1,inorder,index+1,r2);return root;}public TreeNode buildTree(int[] preorder, int[] inorder) {map = new HashMap<>();for (int i = 0; i < inorder.length; i++) {map.put(inorder[i], i);}return dfs(preorder, 0, preorder.length, inorder, 0, inorder.length);}}

654. 最大二叉树

class Solution {TreeNode dfs(int[] nums, int l, int r) {if (l >= r) {return null;}int MAX = -1;int index = -1;for (int i = l; i < r; i++) {if (nums[i] > MAX) {MAX = nums[i];index = i;}}TreeNode root = new TreeNode(MAX);root.left = dfs(nums, l, index);root.right = dfs(nums, index + 1, r);return root;}public TreeNode constructMaximumBinaryTree(int[] nums) {TreeNode root = dfs(nums, 0, nums.length);return root;}}

617. 合并二叉树

image-20221009092020039

class Solution {public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {if (root1 == null) {return root2;}if (root2 == null) {return root1;}root1.val += root2.val;root1.left = mergeTrees(root1.left,root2.left);root1.right = mergeTrees(root1.right,root2.right);return root1;}}

700. 二叉搜索树中的搜索

image-20221009094736048

class Solution {public TreeNode searchBST(TreeNode root, int val) {if(root == null){return null;}if(root.val == val){return root;}if(val < root.val){return searchBST(root.left,val);}else{return searchBST(root.right,val);}}}

8. 验证二叉搜索树

image-20221009100132138

class Solution {boolean ans = true;public void f(TreeNode root, long lower, long upper) {if (root.val <= lower || root.val >= upper) {ans = false;}if (root.left != null) {f(root.left, lower, root.val);}if (root.right != null) {f(root.right, root.val, upper);}}public boolean isValidBST(TreeNode root) {f(root, Long.MIN_VALUE, Long.MAX_VALUE);if (ans) {return true;} else {return false;}}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_20524.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【Golang开发面经】蔚来(两轮技术面)

文章目录一面1. channel 缓冲与非缓冲2. mysql引擎3. 索引如何建立&#xff1f;4. linux 如何看进程5. redis 字符串的底层6. 线程池理解7. 线程池的拒绝策略8.悲观锁&#xff0c;乐观锁9. HTTP 各个版本的区别10. HTTP2.0之前怎么实现服务器推送机制&#xff1f;11. websocket…

[操作系统] 启动

启动 一、通电 由于内存是随机存储器&#xff08;Random access memory&#xff0c;RAM&#xff09;&#xff0c;属于易失性存储器&#xff0c;未通电时&#xff0c;RAM中不会有任何内容&#xff0c;因此刚一通电&#xff0c;RAM不可能有任何实际信息。计算机硬件厂商在只读存…

信创浪潮下,看看大公司是如何建立数据安全保护体系的?

信创&#xff0c;即信息技术应用创新产业&#xff0c;它是数据安全、网络安全的基础&#xff0c;也是新基建的重要组成部分。信创涉及到的行业包括IT基础设施&#xff1a;CPU芯片、服务器、存储、交换机、路由器、各种云和相关服务内容&#xff0c;基础软件&#xff1a;数据库、…

1.ROS机器视觉:单目摄像头的调用与标定

(1条消息) ROS改错&#xff1a;vm虚拟机中调用摄像头失败_机械专业的计算机小白的博客-CSDN博客https://blog.csdn.net/wzfafabga/article/details/127204106?spm1001.2014.3001.5502 首先保证摄像头是可调用的。 1.安装usb_cam驱动 sudo apt-get install ros-melodic-usb-…

数据导入导出功能的测试点

【数据导入功能】 一、操作按钮校验 1、导入按钮生效 2、取消导入按钮生效 二、导入模板校验 1、文件数量 1&#xff09;不传模板&#xff1a;点确认时提示错误 2&#xff09;传模板&#xff1a;只支持单文件 or 还支持多文件同时导入 2、文件格式 只支持xlsx文件 or 还支…

HTML学生个人网站作业设计 学生大学生活网页设计作品 学生个人网页模板 简单个人主页成品 div+css个人网页制作

&#x1f329;️ 精彩专栏推荐&#x1f447;&#x1f3fb;&#x1f447;&#x1f3fb;&#x1f447;&#x1f3fb; &#x1f482; 作者主页: 【进入主页—&#x1f680;获取更多源码】 &#x1f393; web前端期末大作业&#xff1a; 【&#x1f4da;HTML5网页期末作业 (1000套…

Java项目:ssh网上便利店系统

作者主页&#xff1a;夜未央5788 简介&#xff1a;Java领域优质创作者、Java项目、学习资料、技术互助 文末获取源码 项目介绍 该项目分为前后台。非maven项目&#xff1b; 前台主要功能包括&#xff1a; 会员登录、注册、商品展示、加入购物车、会员中心、我的订单、我的地址…

【跟学C++】C++队列——queue类(Study13)

文章目录1、队列2、队列--queue类的使用2.1 实例化queue2.2 queue的成员函数3、优先级队列--priority_queue类的使用3.1 实例化priority_queue3.1 priority_queued的成员函数4、总结 【说明】 大家好&#xff0c;本专栏主要是跟学C内容&#xff0c;自己学习了这位博主【 AI菌】…

多测师肖sir_高级讲师_第2个月第21讲解jmeter安装

一、安装流程&#xff1a; 1、安装jdk &#xff08;linux&#xff0c;windows上&#xff09;&#xff0c;jdk编译java语言&#xff0c; 2、jdk环境配置&#xff0c;dos中java -version 查看jdk版本 3、下载jmeter包&#xff0c;解压&#xff0c;bin 目录 &#xff0c;jmeter.ba…

从零开始配置vim(25)——关于 c++ python 的配置

从9月份到国庆这段时间,因为得了女儿,于是回老家帮忙料理家事以及陪伴老婆和女儿。一时之间无暇顾及该系列教程的更新。等我回来的时候发现很多小伙伴私信我催更。在这里向支持本人这一拙劣教程的各位小伙伴表示真诚的感谢。言归正传,让我们开始吧 之前我们根据lua语言配置了…

(附源码)计算机毕业设计ssm电子购物商城

项目运行 环境配置&#xff1a; Jdk1.8 Tomcat7.0 Mysql HBuilderX&#xff08;Webstorm也行&#xff09; Eclispe&#xff08;IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持&#xff09;。 项目技术&#xff1a; SSM mybatis Maven Vue 等等组成&#xff0c;B/S模式 M…

【DL】第 11 章:自动驾驶汽车的深度学习

&#x1f50e;大家好&#xff0c;我是Sonhhxg_柒&#xff0c;希望你看完之后&#xff0c;能对你有所帮助&#xff0c;不足请指正&#xff01;共同学习交流&#x1f50e; &#x1f4dd;个人主页&#xff0d;Sonhhxg_柒的博客_CSDN博客 &#x1f4c3; &#x1f381;欢迎各位→点赞…

《uni-app》一个非canvas的飞机对战小游戏-启动页

这是一个没有套路的前端博主&#xff0c;热衷各种前端向的骚操作&#xff0c;经常想到哪就写到哪&#xff0c;如果有感兴趣的技术和前端效果可以留言&#xff5e;博主看到后会去代替大家踩坑的&#xff5e;接下来的几篇都是uni-app的小实战&#xff0c;有助于我们更好的去学习u…

基于微信小程序的校园失物招领寻物启事系统 java uniapp 小程序

随着信息化时代的到来,管理系统都趋向于智能化、系统化,微信小程序校园失物招领也不例外,但目前国内的市场仍都使用人工管理,市场规模越来越大,同时信息量也越来越庞大,人工管理显然已无法应对时代的变化,而微信小程序校园失物招领能很好地解决这一问题,轻松应对校园失物招领平…

老项目vue2.x误用了vue3的插件问题

老项目vue2.x误用了vue3的插件问题背景插件vue-template-compilervue-loader问题回溯总结背景 vue3出来两年多了&#xff0c;它刚出来的时候&#xff0c;vue3相比vue2似乎并没有想像中那样受大家欢迎。因为两个版本的构架上相差太大了&#xff0c;许多的API都不兼容&#xff0…

洛谷题单 Part 2.4 分治

分治 即分而治之 将大问题化解为小问题逐一求解 这种题没有固定的模板 只有分治的思想 所以在做题的时候应当多想如何将一个大问题化解成若干个子问题进行求解 直接上题了 P1226 【模板】快速幂||取余运算 非常经典的分治问题 常规算法求aba^bab要O(b)O(b)O(b)的时间复杂度 我…

Mybatis常见查询总结,仅限于初级程序员阅读

情况描述&#xff1a; 本人初次接触Mybatis&#xff0c;然后对于其中的一些基础查询做一些简单总结&#xff0c;一次用来记录他的用法&#xff0c;便于以后查漏补缺。 1、Mybatis中查询特定的列:&#xff08;单列&#xff09; 如果查询指定列为Long类型&#xff0c;那么在re…

游戏合作伙伴专题:BreederDAO 与 Affyn一起重构现实生活

BreederDAO 团队很宣布与 Affyn 建立了新的合作关系&#xff0c;Affyn 是一家位于新加坡的公司&#xff0c;开发了基于地理位置的增强现实移动游戏。 移动元宇宙 Affyn 团队由来自 EA、任天堂、迪士尼和星巴克等顶级游戏、娱乐和生活方式公司的资深员工组成。他们洞悉了目前边玩…

html5网页设计作业代码 大学生校园网站制作 学校官网制作html

&#x1f329;️ 精彩专栏推荐&#x1f447;&#x1f3fb;&#x1f447;&#x1f3fb;&#x1f447;&#x1f3fb; &#x1f482; 作者主页: 【进入主页—&#x1f680;获取更多源码】 &#x1f393; web前端期末大作业&#xff1a; 【&#x1f4da;HTML5网页期末作业 (1000套…

性能大PK count(*)、count(1)和count(列)

最近的工作中&#xff0c;我听到组内两名研发同学在交流数据统计性能的时候&#xff0c;聊到了以下内容&#xff1a; 数据统计你怎么能用 count() 统计数据呢&#xff0c;count() 太慢了&#xff0c;要是把数据库搞垮了那不就完了么&#xff0c;赶紧改用 count(1)&#xff0c;这…