Leetcode:二叉树

94. 二叉树的中序遍历

class Solution {public List<Integer> inorderTraversal(TreeNode root) {TreeNode cur = root;Stack<TreeNode> stack = new Stack<>();List<Integer> list = new ArrayList<>();while (!stack.isEmpty() || cur != null) {while (cur != null) {stack.push(cur);cur = cur.left;}cur = stack.pop();list.add(cur.val);cur = cur.right;}return list;}
}

230. 二叉搜索树中第 K 小的元素

class Solution {public int kthSmallest(TreeNode root, int k) {Stack<TreeNode> stack = new Stack<>();int ans=0;TreeNode cur = root;while(!stack.isEmpty() || cur!=null){while(cur!=null){stack.push(cur);cur=cur.left;}cur=stack.pop();k--;if(k==0){ans=cur.val;return ans;}//必要的一步cur=cur.right;}return -1;}
}

104. 二叉树的最大深度


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

226. 翻转二叉树

class Solution {public TreeNode invertTree(TreeNode root) {if(root==null) return null;TreeNode temp=root.left;root.left=root.right;root.right=temp;invertTree(root.left);invertTree(root.right);return root;}
}

101. 对称二叉树


class Solution {public boolean isSymmetric(TreeNode root) {if(root==null) return true;return dfs(root.left, root.right);}public boolean dfs(TreeNode left, TreeNode right){if(left==null && right==null) return true;//两个都nullif(left==null || right==null) return false;//一个null,另一个非空if(left.val!=right.val) return false;//两个都非空return dfs(left.left, right.right) && dfs(right.left, left.right);}
}

543. 二叉树的直径

class Solution {private int maxDepth=0;public int diameterOfBinaryTree(TreeNode root) {if(root==null) return 0;depth(root);return maxDepth;}public int depth(TreeNode root){if(root==null) return 0;int lH = depth(root.left);int rH = depth(root.right);//注意:这里的lH+rH正好是路径长度,应该是lH+rH+1-1,加和减的1都是重复的根节点maxDepth=Math.max(maxDepth, lH+rH);return Math.max(lH, rH)+1;}
}

102. 二叉树的层序遍历

class Solution {public List<List<Integer>> levelOrder(TreeNode root) {Queue<TreeNode> queue = new ArrayDeque<>();List<List<Integer>> ans = new ArrayList<>();if(root!=null){queue.add(root);}while(!queue.isEmpty()){int n = queue.size();List<Integer> arr = new ArrayList<>();for(int i=0; i<n; i++){TreeNode cur = queue.poll();arr.add(cur.val);if(cur.left!=null)queue.add(cur.left);if(cur.right!=null)queue.add(cur.right);}ans.add(arr);}return ans;}
}

199. 二叉树的右视图

class Solution {public List<Integer> rightSideView(TreeNode root) {Queue<TreeNode> queue = new ArrayDeque<>();List<Integer> ans = new ArrayList<>();if (root != null)queue.offer(root);while (!queue.isEmpty()) {int n = queue.size();for (int i = 0; i < n ; i++) {TreeNode cur = queue.poll();if (cur.left != null)queue.offer(cur.left);if (cur.right != null)queue.offer(cur.right);if(i==n-1)ans.add(cur.val);}}return ans;}
}

108. 将有序数组转换为二叉搜索树

构造平衡二叉搜索树!| LeetCode:108.将有序数组转换为二叉搜索树_哔哩哔哩_bilibili

class Solution {public TreeNode sortedArrayToBST(int[] nums) {return build(nums, 0, nums.length-1);}public TreeNode build(int[] nums, int left, int right){//终止条件: middle-1到最后会比left小, middle+1会比right大if(left>right) return null;int middle = (left+right)/2;TreeNode root = new TreeNode(nums[middle]);root.left = build(nums, left, middle-1);root.right = build(nums, middle+1, right);return root;}
}

110. 平衡二叉树

后序遍历求高度,高度判断是否平衡 | LeetCode:110.平衡二叉树_哔哩哔哩_bilibili

class Solution {public boolean isBalanced(TreeNode root) {int res = dfs(root);return (res==-1) ? false : true;}//后续遍历顺序public int dfs(TreeNode root){if(root==null) return 0;int left = dfs(root.left);if(left==-1) return -1;int right = dfs(root.right);if(right==-1) return -1;if(Math.abs(left-right)>1)return -1;else{return Math.max(left, right) + 1;}}
}

98. 验证二叉搜索树(mid)

你对二叉搜索树了解的还不够! | LeetCode:98.验证二叉搜索树_哔哩哔哩_bilibili

class Solution {long pre = Long.MIN_VALUE;public boolean isValidBST(TreeNode root) {if(root==null) return true;//左boolean left = isValidBST(root.left);//中if(root.val>pre)pre = root.val;elsereturn false;//右boolean right = isValidBST(root.right);return left && right;}
}

114. 二叉树展开为链表

class Solution {public void flatten(TreeNode root) {TreeNode cur = root;if (root == null)return;while (cur != null) {if (cur.left != null) {TreeNode p = cur.left;//移动到cur节点的left的最右侧节点while (p.right != null)p = p.right;//做连接p.right = cur.right;cur.right = cur.left;cur.left = null;}//做cur左边的断开cur = cur.right;}}
}

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

坑很多!来看看你掉过几次坑 | LeetCode:106.从中序与后序遍历序列构造二叉树_哔哩哔哩_bilibili

class Solution {public TreeNode buildTree(int[] preorder, int[] inorder) {int len = preorder.length;if(len==0) return null;int rootValue=preorder[0];TreeNode root = new TreeNode(rootValue);//获取根节点indexint rootIndex = 0;for(int i=0; i<len; i++){if(inorder[i]==rootValue){rootIndex=i;break;}}int left_len = rootIndex;int right_len = len-rootIndex-1;;int[] preorder_left = Arrays.copyOfRange(preorder, 1, rootIndex+1);int[] preorder_right = Arrays.copyOfRange(preorder, rootIndex+1, len);int[] inorder_left = Arrays.copyOfRange(inorder, 0, rootIndex);        int[] inorder_right = Arrays.copyOfRange(inorder, rootIndex+1, len);//递归左右子树root.left = buildTree(preorder_left, inorder_left);root.right = buildTree(preorder_right, inorder_right);return root;}
}

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

坑很多!来看看你掉过几次坑 | LeetCode:106.从中序与后序遍历序列构造二叉树_哔哩哔哩_bilibili


class Solution {public TreeNode buildTree(int[] inorder, int[] postorder) {int len = postorder.length;if(len==0) return null;int rootValue=postorder[len-1];TreeNode root = new TreeNode(rootValue);//获取根节点indexint rootIndex = 0;for(int i=0; i<len; i++){if(inorder[i]==rootValue){rootIndex=i;break;}}int left_len = rootIndex;int right_len = len-rootIndex-1;;//前序+中序 或者 后序+中序 仅仅是切分数组有区别int[] postorder_left = Arrays.copyOfRange(postorder, 0, left_len);int[] postorder_right = Arrays.copyOfRange(postorder, rootIndex, left_len+right_len);int[] inorder_left = Arrays.copyOfRange(inorder, 0, rootIndex);        int[] inorder_right = Arrays.copyOfRange(inorder, rootIndex+1, len);//递归左右子树root.left = buildTree(inorder_left, postorder_left);root.right = buildTree(inorder_right, postorder_right);return root;}
}

437. 路径总和 III(⭐)

不用前缀和:

小姐姐刷题-Leetcode 437 路径总和 III_哔哩哔哩_bilibili

class Solution {private int res = 0;public void dfs(TreeNode root, long sum) {if (root == null)return;if (root.val == sum) {res++;}dfs(root.left, sum-root.val);dfs(root.right, sum-root.val);}//这里的int需要改成longpublic int pathSum(TreeNode root, long targetSum) {if (root != null) {dfs(root, targetSum);// 这里targetSum不需要减当前节点的值,因为路径不一定从根节点开始pathSum(root.left, targetSum);pathSum(root.right, targetSum);}return res;}
}
常规:前缀和+hashmap

力扣 leetcode 437. 路径总和 III/dfs+前缀和+hashmap/建议倍速观看/技术岗秋招之路,自我反思/刷题_哔哩哔哩_bilibili

class Solution {int res=0;long targetSum;Map<Long, Integer> map;public int pathSum(TreeNode root, long targetSum) {this.targetSum = targetSum;map=new HashMap<>();map.put(0L, 1); //long类型dfs(root, 0);return res;}public void dfs(TreeNode root, long sum){if(root==null) return;sum += root.val;if(map.containsKey(sum-targetSum)){res+=map.get(sum-targetSum);}map.put(sum, map.getOrDefault(sum, 0)+1 );dfs(root.left, sum);dfs(root.right, sum);//回溯map.put(sum, map.get(sum)-1);}}

236. 二叉树的最近公共祖先

【自底向上查找,有点难度! | LeetCode:236. 二叉树的最近公共祖先】自底向上查找,有点难度! | LeetCode:236. 二叉树的最近公共祖先_哔哩哔哩_bilibili


class Solution {public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {if(root==null) return root;if(root==p || root==q) return root;//采用后续遍历://先处理左右TreeNode left = lowestCommonAncestor(root.left, p, q);TreeNode right = lowestCommonAncestor(root.right, p, q);/然后处理中节点,要基于上面“左右”的结果来判断“中”,所以是后续遍历if(left==null && right!=null) return right;if(left!=null && right==null) return left; if(left==null && left==null) return null;return root;}
}

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

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

相关文章

SQL:Constraint(约束)

目录 &#x1f3af; 什么是 Constraint&#xff1f; MySQL 中常见的约束类型&#xff1a; 1. PRIMARY KEY 2. FOREIGN KEY 3. UNIQUE 4. NOT NULL 5. DEFAULT 6. CHECK&#xff08;MySQL 8.0&#xff09; 7. AUTO_INCREMENT &#x1f3af; 什么是 Constraint&#xf…

数据库数据恢复——sql server数据库被加密怎么恢复数据?

SQL server数据库数据故障&#xff1a; SQL server数据库被加密&#xff0c;无法使用。 数据库MDF、LDF、log日志文件名字被篡改。 数据库备份被加密&#xff0c;文件名字被篡改。 SQL server数据库数据恢复过程&#xff1a; 1、将所有数据库做完整只读备份。后续所有数据恢…

MySQL 用 limit 影响性能的优化方案

一.使用索引覆盖扫描 如果我们只需要查询部分字段&#xff0c;而不是所有字段&#xff0c;我们可以尝试使用索引覆盖扫描&#xff0c;也就是让查询所需的所有字段都在索引中&#xff0c;这样就不需要再访问数据页&#xff0c;减少了随机 I/O 操作。 例如&#xff0c;如果我们…

【算法笔记】并查集详解

&#x1f680; 并查集&#xff08;Union-Find&#xff09;详解&#xff1a;原理、实现与优化 并查集&#xff08;Union-Find&#xff09;是一种非常高效的数据结构&#xff0c;用于处理动态连通性问题&#xff0c;即判断若干个元素是否属于同一个集合&#xff0c;并支持集合合…

鸿蒙HarmonyOS埋点SDK,ClkLog适配鸿蒙埋点分析

ClkLog埋点分析系统&#xff0c;是一种全新的、开源的洞察方案&#xff0c;它能够帮助您捕捉每一个关键数据点&#xff0c;确保您的决策基于最准确的用户行为分析。技术人员可快速搭建私有的分析系统。 ClkLog鸿蒙埋点SDK通过手动埋点的方式实现HarmonyOS 原生应用的前端数据采…

JMeter的关联

关联&#xff1a;上一个请求的响应结果和下一个请求的数据有关系 xpath提取器 适用场景 HTML/XML文档结构化数据&#xff1a; 适用于从HTML或XML文档中提取结构化数据。例如&#xff0c;提取表格中的数据、列表中的项目等。示例&#xff1a;从HTML表格中提取所有行数据。 …

Spring Security 权限配置详解

&#x1f31f;Spring Security 权限配置详解&#xff1a;从基础到进阶 Spring Security 是一个功能强大、可高度自定义的安全框架&#xff0c;主要用于为基于 Spring 的应用程序提供身份验证和授权功能。 本篇文章将带你深入理解 Spring Security 的权限配置机制&#xff0c;掌…

pycharm中安装Charm-Crypto

一、安装依赖 1、安装gcc、make、perl sudo apt-get install gcc sudo apt-get install make sudo apt-get install perl #检查版本 gcc -v make -v perl -v 2、安装依赖库m4、flex、bison(如果前面安装过pypbc的话,应该已经装过这些包了) sudo apt-get update sudo apt…

【MCAL】AUTOSAR架构下基于SPI通信的驱动模块详解-以TJA1145为例

目录 前言 正文 1.TJA1145驱动代码中的SPI协议设计 1.1 对SPI Driver的依赖 1.2 对SPI配置的依赖 1.2.1 SpiExternalDevice 1.2.2 Channel_x 1.2.3 Job_x 1.2.4 Sequence N 1.2.5 Sequence M 1.2.6 Sequence L 1.2.7 小结 2.基于Vector驱动代码的SPI配置 2.1 SPI引…

JavaScript:BOM编程

今天我要介绍的是JS中有关于BOM编程的知识点内容&#xff1a;BOM编程&#xff1b; 介绍&#xff1a;BOM全名&#xff08;Browser Object Model&#xff08;浏览器对象模型&#xff09;&#xff09;。 是浏览器提供的与浏览器窗口交互的接口&#xff0c;其核心对象是 window。与…

Memcached缓存系统:从部署到实战应用指南

#作者&#xff1a;猎人 文章目录 一、安装libevent二、安装配置memcached三、安装Memcache的PHP扩展四、使用libmemcached的客户端工具五、Nginx整合memcached:六、php将会话保存至memcached Memcached是一款开源、高性能、分布式内存对象缓存系统&#xff0c;可应用各种需要缓…

解决前后端时区不一致问题

前后端时区不一致导致&#xff1a; 》数据不显示在前端 》页面显示时间有误 》一些对时间有要求的方法&#xff0c;无法正确执行&#xff0c;出现null值&#xff0c;加上我们对null值有判断/注解&#xff0c;程序就会报错中断&#xff0c;以为是业务逻辑问题&#xff0c;其实…

35.Java线程池(线程池概述、线程池的架构、线程池的种类与创建、线程池的底层原理、线程池的工作流程、线程池的拒绝策略、自定义线程池)

一、线程池概述 1、线程池的优势 线程池是一种线程使用模式&#xff0c;线程过多会带来调度开销&#xff0c;进而影响缓存局部性和整体性能&#xff0c;而线程池维护着多个线程&#xff0c;等待着监督管理者分配可并发执行的任务&#xff0c;这避免了在处理短时间任务时创建与…

驱动开发硬核特训 · Day 6 : 深入解析设备模型的数据流与匹配机制 —— 以 i.MX8M 与树莓派为例的实战对比

&#x1f50d; B站相应的视屏教程&#xff1a; &#x1f4cc; 内核&#xff1a;博文视频 - 从静态绑定驱动模型到现代设备模型 主题&#xff1a;深入解析设备模型的数据流与匹配机制 —— 以 i.MX8M 与树莓派为例的实战对比 在上一节中&#xff0c;我们从驱动框架的历史演进出…

Blender安装基础使用教程

本博客记录安装Blender和基础使用&#xff0c;可以按如下操作来绘制标靶场景、道路标识牌等。 目录 1.安装Blender 2.创建面板资源 步骤 1: 设置 Blender 场景 步骤 2: 创建一个平面 步骤 3: 将 PDF 转换为图像 步骤 4-方法1: 添加材质并贴图 步骤4-方法2&#xff1a;创…

智能手机功耗测试

随着智能手机发展,用户体验对手机的续航功耗要求越来越高。需要对手机进行功耗测试及分解优化,将手机的性能与功耗平衡。低功耗技术推动了手机的用户体验。手机功耗测试可以采用powermonitor或者NI仪表在功耗版上进行测试与优化。作为一个多功能的智能终端,手机的功耗组成极…

从代码学习深度学习 - 多头注意力 PyTorch 版

文章目录 前言一、多头注意力机制介绍1.1 工作原理1.2 优势1.3 代码实现概述二、代码解析2.1 导入依赖序列掩码函数2.2 掩码 Softmax 函数2.3 缩放点积注意力2.4 张量转换函数2.5 多头注意力模块2.6 测试代码总结前言 在深度学习领域,注意力机制(Attention Mechanism)是自然…

学术版 GPT 网页

学术版 GPT 网页 1. 学术版 GPT 网页非盈利版References https://academic.chatwithpaper.org/ 1. 学术版 GPT 网页非盈利版 arXiv 全文翻译&#xff0c;免费且无需登录。 更换模型 System prompt: Serve me as a writing and programming assistant. 界面外观 References …

MarkDown 输出表格的方法

MarkDown用来输出表格很简单&#xff0c;比Word手搓表格简单多了&#xff0c;而且方便修改。 MarkDown代码&#xff1a; |A|B|C|D| |:-|-:|:-:|-| |1|b|c|d| |2|b|c|d| |3|b|c|d| |4|b|c|d| |5|b|c|d|显示效果&#xff1a; ABCD1bcd2bcd3bcd4bcd5bcd A列强制左对齐&#xf…

MetaGPT深度解析:重塑AI协作开发的智能体框架实践指南

一、框架架构与技术突破 1.1 系统架构设计 graph TBA[自然语言需求] --> B(需求解析引擎)B --> C{角色路由系统}C --> D[产品经理Agent]C --> E[架构师Agent]C --> F[工程师Agent]D --> G[PRD文档]E --> H[架构图]F --> I[代码文件]G --> J[知识共…