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.pswp.cn/bicheng/76812.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/76812.shtml
英文地址,請注明出處:http://en.pswp.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[知識共…