代碼隨想錄——二叉樹(一)

文章目錄

      • 二叉樹遍歷
        • 先序遍歷
        • 中序遍歷
        • 后序遍歷
        • 層序遍歷
        • 層序遍歷Ⅱ
        • 二叉樹的右視圖
        • 二叉樹的層平均值
        • N插樹的層序遍歷
        • 在每個樹行中找最大值
        • 填充每個節點的下一個右側節點指針
        • 填充每個節點的下一個右側節點指針 II

二叉樹遍歷

先序遍歷

二叉樹先序遍歷

遞歸形式

/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     struct TreeNode *left;*     struct TreeNode *right;* };*/
/*** Note: The returned array must be malloced, assume caller calls free().*/
int ans[100];
int cnt=0;
void PreOrder(struct TreeNode* root){if(root==NULL)return;ans[cnt++]=root->val;PreOrder(root->left);PreOrder(root->right);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize) {cnt=0;PreOrder(root);*returnSize=cnt;return ans;
}

非遞歸形式(迭代法)

/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     struct TreeNode *left;*     struct TreeNode *right;* };*/
/*** Note: The returned array must be malloced, assume caller calls free().*/int* preorderTraversal(struct TreeNode* root, int* returnSize) {int *ans=malloc(sizeof(int)*100);*returnSize=0;if(root==NULL)return ans;struct TreeNode* st[100];struct TreeNode* node=root;int top=0;while(top>0||node!=NULL){while(node!=NULL){ans[(*returnSize)++]=node->val;st[top++]=node;node=node->left;}node=st[--top]->right;}return ans;
}
中序遍歷

二叉樹中序遍歷

遞歸

/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     struct TreeNode *left;*     struct TreeNode *right;* };*/
/*** Note: The returned array must be malloced, assume caller calls free().*/
void Inorder(struct TreeNode* root,int *ans,int *cnt){if(root==NULL)return;Inorder(root->left,ans,cnt);ans[(*cnt)++]=root->val;Inorder(root->right,ans,cnt);
}
int* inorderTraversal(struct TreeNode* root, int* returnSize) {int *ans=malloc(sizeof(int)*100);int cnt=0;Inorder(root,ans,&cnt);*returnSize=cnt;return ans;
}

非遞歸

/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     struct TreeNode *left;*     struct TreeNode *right;* };*/
/*** Note: The returned array must be malloced, assume caller calls free().*/
int* inorderTraversal(struct TreeNode* root, int* returnSize) {int *ans=malloc(sizeof(int)*100);*returnSize=0;if(root==NULL)return ans;struct TreeNode *st[100];struct TreeNode *node=root;int top=0;while(top>0||node!=NULL){while(node!=NULL){st[top++]=node;node=node->left;}node=st[--top];ans[(*returnSize)++]=node->val;node=node->right;}return ans;
}
后序遍歷

二叉樹后序遍歷

遞歸

/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     struct TreeNode *left;*     struct TreeNode *right;* };*/
/*** Note: The returned array must be malloced, assume caller calls free().*/
void PostOrder(struct TreeNode* root,int *ans,int *cnt){if(root==NULL)return;PostOrder(root->left,ans,cnt);PostOrder(root->right,ans,cnt);ans[(*cnt)++]=root->val;
}
int* postorderTraversal(struct TreeNode* root, int* returnSize) {int *ans=malloc(sizeof(int)*100);int cnt=0;PostOrder(root,ans,&cnt);*returnSize=cnt;return ans;
}

非遞歸

/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     struct TreeNode *left;*     struct TreeNode *right;* };*/
/*** Note: The returned array must be malloced, assume caller calls free().*/int* postorderTraversal(struct TreeNode* root, int* returnSize) {int *ans=malloc(sizeof(int)*100);*returnSize=0;if(root==NULL)return ans;struct TreeNode* st[100];struct TreeNode* node=root;struct TreeNode* pre=NULL;int top=0;while(top>0||node!=NULL){while(node!=NULL){st[top++]=node;node=node->left;}node=st[--top];if(node->right==NULL||node->right==pre){ans[(*returnSize)++]=node->val;pre=node;node=NULL;}else{st[top++]=node;node=node->right;}}return ans;
}
層序遍歷

二叉樹層序遍歷

/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     struct TreeNode *left;*     struct TreeNode *right;* };*/
/*** Return an array of arrays of size *returnSize.* The sizes of the arrays are returned as *returnColumnSizes array.* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().*/
int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes) {//returnSize——二叉樹高度//returnColumnSizes——每層的節點數struct TreeNode *queue[2000];int front=0;int tail=0;int **ans=malloc(sizeof(int*)*2000);*returnColumnSizes=malloc(sizeof(int)*2000);queue[front++]=root;*returnSize=0;if(root==NULL)return ans;while(front>tail){int t=front;int cnt=0;//記錄該層節點個數ans[*returnSize]=malloc(sizeof(int)*(t-tail));for(tail;tail<t;tail++){//遍歷當前層的節點,并將下一層節點放入struct TreeNode* node=queue[tail];ans[*returnSize][cnt++]=node->val;if(node->left)queue[front++]=node->left;if(node->right)queue[front++]=node->right;}(*returnColumnSizes)[(*returnSize)++]=cnt;}return ans;
}
層序遍歷Ⅱ

二叉樹層序遍歷Ⅱ

思路:與上面的思路類似,只是在后面把結果反轉

/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     struct TreeNode *left;*     struct TreeNode *right;* };*/
int** levelOrderBottom(struct TreeNode* root, int* returnSize, int** returnColumnSizes) {if (root == NULL) {*returnSize = 0;*returnColumnSizes = NULL;return NULL;}struct TreeNode** queue = malloc(sizeof(struct TreeNode*) * 2000); // 動態分配隊列int front = 0, tail = 0;int** ans = malloc(sizeof(int*) * 2000); // 存儲層次遍歷結果*returnColumnSizes = malloc(sizeof(int) * 2000); // 存儲每層的節點數*returnSize = 0;queue[front++] = root; // 根節點入隊while (front > tail) {int levelSize = front - tail; // 當前層的節點數ans[*returnSize] = malloc(sizeof(int) * levelSize); // 分配當前層的存儲空間(*returnColumnSizes)[*returnSize] = levelSize; // 記錄當前層的節點數for (int i = 0; i < levelSize; i++) {struct TreeNode* node = queue[tail++];ans[*returnSize][i] = node->val; // 存儲當前節點的值if (node->left) queue[front++] = node->left; // 左子節點入隊if (node->right) queue[front++] = node->right; // 右子節點入隊}(*returnSize)++; // 處理完一層}// 反轉結果int** res = malloc(sizeof(int*) * (*returnSize));for (int i = 0; i < *returnSize; i++) {int level = *returnSize - 1 - i;res[i] = ans[level]; // 直接使用 ans 的內存,避免重復分配}// 反轉 returnColumnSizesfor (int i = 0; i < *returnSize / 2; i++) {int temp = (*returnColumnSizes)[i];(*returnColumnSizes)[i] = (*returnColumnSizes)[*returnSize - 1 - i];(*returnColumnSizes)[*returnSize - 1 - i] = temp;}free(queue); // 釋放隊列內存return res;
}
二叉樹的右視圖

題目鏈接

思路:其實就是取每一層的最右邊節點的值,在層序遍歷時只保存最后一個值就行了。

/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     struct TreeNode *left;*     struct TreeNode *right;* };*/
/*** Note: The returned array must be malloced, assume caller calls free().*/int* rightSideView(struct TreeNode* root, int* returnSize) {
//其實就是取每一層最右邊的值struct TreeNode *queue[100];int *ans=malloc(sizeof(int)*100);struct TreeNode* node=root;*returnSize=0;int front=0;int tail=0;queue[front++]=node;if(root==NULL)return ans;while(front>tail){int t=front;while(tail<t){node=queue[tail++];if(node->left)queue[front++]=node->left;if(node->right)queue[front++]=node->right;}ans[(*returnSize)++]=queue[t-1]->val;}    return ans;
}
二叉樹的層平均值

題目鏈接

思路:層次遍歷的時候計算計算一下平均值

/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     struct TreeNode *left;*     struct TreeNode *right;* };*/
/*** Note: The returned array must be malloced, assume caller calls free().*/
double* averageOfLevels(struct TreeNode* root, int* returnSize) {double *ans=malloc(sizeof(int)*10005);struct TreeNode* queue[10005];int front=0,tail=0;struct TreeNode *node=root;*returnSize=0;queue[front++]=node;if(root==NULL)return ans;while(front>tail){double avg=0;int t=front;double num=front-tail;//當前層節點數while(tail<t){node=queue[tail++];if(node->left)queue[front++]=node->left;if(node->right)queue[front++]=node->right;avg+=(double)node->val;}avg/=num;ans[(*returnSize)++]=avg;}return ans;
}
N插樹的層序遍歷

題目鏈接

思路:paper tiger,和二叉樹的層次遍歷的區別在于訪問孩子節點的方式不同

/*** Definition for a Node.* struct Node {*     int val;*     int numChildren;*     struct Node** children;* };*//*** Return an array of arrays of size *returnSize.* The sizes of the arrays are returned as *returnColumnSizes array.* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().*/
int** levelOrder(struct Node* root, int* returnSize, int** returnColumnSizes) {struct Node* queue[10005];int front=0,tail=0;int **ans=malloc(sizeof(int*)*1000);struct Node* node=root;*returnSize=0;*returnColumnSizes=malloc(sizeof(int)*1000);if(root==NULL)return ans;queue[front++]=node;while(front>tail){int len=front-tail;ans[*returnSize]=malloc(sizeof(int)*len);int cnt=0;//保存訪問到該層的第幾個節點int t=front;while(tail<t){node=queue[tail++];ans[*returnSize][cnt++]=node->val;if(node->numChildren>0){//將孩子節點放入隊列    int n=node->numChildren;for(int i=0;i<n;i++){queue[front++]=(node->children)[i];}}}(*returnColumnSizes)[(*returnSize)++]=len;}return ans;
}
在每個樹行中找最大值

題目鏈接

思路:由上面求平均值改寫,將求平均值的邏輯改為求最大值就行啦! >v<

/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     struct TreeNode *left;*     struct TreeNode *right;* };*/
/*** Note: The returned array must be malloced, assume caller calls free().*/
int* largestValues(struct TreeNode* root, int* returnSize) {int *ans=malloc(sizeof(int)*10005);struct TreeNode* queue[10005];int front=0,tail=0;struct TreeNode *node=root;*returnSize=0;queue[front++]=node;if(root==NULL)return ans;while(front>tail){int Max=queue[tail]->val;int t=front;while(tail<t){node=queue[tail++];if(node->left)queue[front++]=node->left;if(node->right)queue[front++]=node->right;if(node->val>Max)Max=node->val;}ans[(*returnSize)++]=Max;}return ans;
}
填充每個節點的下一個右側節點指針

題目鏈接

思路:還是二叉樹層序遍歷的思路,每一層的節點用next指針連接就好,不要忘記邊界哦。

/*** Definition for a Node.* struct Node {*     int val;*     struct Node *left;*     struct Node *right;*     struct Node *next;* };*/struct Node* connect(struct Node* root) {//實際上只需要填充next指針即可struct Node* queue[5000];int front=0;int tail=0;if(root==NULL)return root;queue[front++]=root;while(front>tail){int t=front;while(tail<t){if(queue[tail]->left)queue[front++]=queue[tail]->left;if(queue[tail]->right)queue[front++]=queue[tail]->right;if(tail<t-1)queue[tail]->next=queue[tail+1];else queue[tail]->next=NULL;tail++;}}return root;;
}
填充每個節點的下一個右側節點指針 II

填充每個節點的下一個右側節點指針 II

思路:直接用上一題代碼就行了,但是要把隊列內存擴大。。。hahaha

/*** Definition for a Node.* struct Node {*     int val;*     struct Node *left;*     struct Node *right;*     struct Node *next;* };*/struct Node* connect(struct Node* root) {struct Node* queue[6005];int front=0;int tail=0;if(root==NULL)return root;queue[front++]=root;while(front>tail){int t=front;while(tail<t){if(queue[tail]->left)queue[front++]=queue[tail]->left;if(queue[tail]->right)queue[front++]=queue[tail]->right;if(tail<t-1)queue[tail]->next=queue[tail+1];else queue[tail]->next=NULL;tail++;}}return root;;
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/66807.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/66807.shtml
英文地址,請注明出處:http://en.pswp.cn/web/66807.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

詳細介紹:持續集成與持續部署(CI/CD)技術細節(關鍵實踐、CI/CD管道、優勢與挑戰)

目錄 前言1、 持續集成&#xff08;CI&#xff09;1.1、持續集成的關鍵實踐1.2、持續集成工具1.3、持續集成的優勢 2、持續部署與持續交付&#xff08;CD&#xff09;2.1、持續交付&#xff08;Continuous Delivery&#xff09;2.2、持續部署&#xff08;Continuous Deployment…

Linux 系統服務開機自啟動指導手冊

一、引言 在 Linux 系統中&#xff0c;設置服務開機自啟動是常見的系統配置任務。本文檔詳細介紹了多種實現服務開機自啟動的方法&#xff0c;包括 systemctl 方式、通用腳本方式、crontab 方案等&#xff0c;并提供了生產環境下的方案建議和開機啟動腳本示例。 二、systemct…

Java如何向http/https接口發出請求

用Java發送web請求所用到的包都在java.net下&#xff0c;在具體使用時可以用如下代碼&#xff0c;你可以把它封裝成一個工具類 import javax.net.ssl.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Outpu…

禁止 iOS 系統瀏覽器雙指放大頁面

網上找到禁止ios縮放的方法基本都試過了,但是還是有bug,如標題所示,下面我將總結一下禁止ios縮放,雙擊縮放的方法。 方法一 在 iOS 10之前&#xff0c;iOS 和 Android 都可以通過一行 meta 標簽來禁止頁面縮放&#xff1a; <meta content"widthdevice-width, initia…

讀西瓜書的數學準備

1&#xff0c;高等數學&#xff1a;會求偏導數就行 2&#xff0c;線性代數&#xff1a;會矩陣運算就行 參考&#xff1a;線性代數--矩陣基本計算&#xff08;加減乘法&#xff09;_矩陣運算-CSDN博客 3&#xff0c;概率論與數理統計&#xff1a;知道啥是隨機變量就行

PLC通信

PLC&#xff08;可編程邏輯控制器&#xff09;通信是指 PLC 與其他設備或系統之間進行數據傳輸和信息交換的過程 一、PLC通信方式 1 &#xff09;串行通信 數據按位順序依次傳輸&#xff0c;只需要一對傳輸線&#xff0c;成本低&#xff0c;傳輸距離長&#xff0c;但速度相對…

C/C++、網絡協議、網絡安全類文章匯總

&#x1f6f8; 文章簡介 本文章主要對本博客的所有文章進行了匯總&#xff0c;方便查找。內容涉及C/C編程&#xff0c;CMake、Makefile、Shell腳本&#xff0c;GUI編程框架MFC和QT&#xff0c;Git版本控制工具&#xff0c;網絡協議基礎知識&#xff0c;網絡安全領域相關知識&a…

java 中多線程、 隊列使用實例,處理大數據業務

場景&#xff1a; 從redis 訂閱數據 調用線程來異步處理數據 直接上代碼 定義線程管理類 import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org…

【自動駕駛】4 智駕生態概述

目錄 1 智駕生態概述 ▲ 關鍵組成部分 ▲ 概述 2 關鍵技術 ▲ 傳感器 ▲ 感知 ▲ 數據閉環 3 未來市場 1 智駕生態概述 智能駕駛生態&#xff0c;簡稱智駕生態&#xff0c;是指圍繞智能駕駛技術的開發、應用、服務和支持所形成的產業體系和合作網絡。 涵蓋了從硬件設…

2025.1.20——一、[RCTF2015]EasySQL1 二次注入|報錯注入|代碼審計

題目來源&#xff1a;buuctf [RCTF2015]EasySQL1 目錄 一、打開靶機&#xff0c;整理信息 二、解題思路 step 1&#xff1a;初步思路為二次注入&#xff0c;在頁面進行操作 step 2&#xff1a;嘗試二次注入 step 3&#xff1a;已知雙引號類型的字符型注入&#xff0c;構造…

”彩色的驗證碼,使用pytesseract識別出來的驗證碼內容一直是空“的解決辦法

問題&#xff1a;彩色的驗證碼&#xff0c;使用pytesseract識別出來的驗證碼內容一直是空字符串 原因&#xff1a;pytesseract只識別黑色部分的內容 解決辦法&#xff1a;先把彩色圖片精確轉換成黑白圖片。再將黑白圖片進行反相&#xff0c;將驗證碼部分的內容變成黑色&#…

Unity3D項目開發中的資源加密詳解

前言 在Unity3D游戲開發中&#xff0c;保護游戲資源不被非法獲取和篡改是至關重要的一環。資源加密作為一種有效的技術手段&#xff0c;可以幫助開發者維護游戲的知識產權和安全性。本文將詳細介紹Unity3D項目中如何進行資源加密&#xff0c;并提供相應的技術詳解和代碼實現。…

RabbitMQ 在實際應用時要注意的問題

1. 冪等性保障 1.1 冪等性介紹 冪等性是數學和計算機科學中某些運算的性質,它們可以被多次應?,?不會改變初始應?的結果. 應?程序的冪等性介紹 在應?程序中,冪等性就是指對?個系統進?重復調?(相同參數),不論請求多少次,這些請求對系統的影響都是相同的效果. ?如數據庫…

AIGC視頻生成明星——Emu Video模型

大家好&#xff0c;這里是好評筆記&#xff0c;公主號&#xff1a;Goodnote&#xff0c;專欄文章私信限時Free。本文詳細介紹Meta的視頻生成模型Emu Video&#xff0c;作為Meta發布的第二款視頻生成模型&#xff0c;在視頻生成領域發揮關鍵作用。 &#x1f33a;優質專欄回顧&am…

Debian 上安裝PHP

1、安裝軟件源拓展工具 apt -y install software-properties-common apt-transport-https lsb-release ca-certificates 2、添加 Ond?ej Sur 的 PHP PPA 源&#xff0c;需要按一次回車&#xff1a; add-apt-repository ppa:ondrej/php 3、更新軟件源緩存&#xff1a; apt-g…

office 2019 關閉word窗口后卡死未響應

最近關閉word文件總是出現卡死未響應的狀態&#xff0c;必須從任務管理器才能殺掉word 進程&#xff0c;然后重新打開word再保存&#xff0c;很是麻煩。&#xff08;#其他特征&#xff0c;在word中打字會特別變慢&#xff0c;敲擊鍵盤半秒才出現字符。&#xff09; office官網…

SecureUtil.aes數據加密工具類

數據加密、解密工具類 包含map和vo的數據轉換 import cn.hutool.core.bean.BeanUtil; import cn.hutool.crypto.SecureUtil;import java.util.HashMap; import java.util.Map;/*** 數據解析**/ public class ParamUtils {/*** 數據解密** param params 參數* param secretKe…

機器學習:支持向量機

支持向量機&#xff08;Support Vector Machine&#xff09;是一種二類分類模型&#xff0c;其基本模型定義為特征空間上的間隔最大的廣義線性分類器&#xff0c;其學習策略便是間隔最大化&#xff0c;最終可轉化為一個凸二次規劃問題的求解。 假設兩類數據可以被 H x : w T x…

SQL-leetcode—1148. 文章瀏覽 I

1148. 文章瀏覽 I Views 表&#xff1a; ---------------------- | Column Name | Type | ---------------------- | article_id | int | | author_id | int | | viewer_id | int | | view_date | date | ---------------------- 此表可能會存在重復行。&#xff08;換句話說…

k8s資源預留

k8s資源預留 https://kubernetes.io/zh-cn/docs/tasks/administer-cluster/reserve-compute-resources/ vim /var/lib/kubelet/config.yamlenforceNodeAllocatable: - pods kubeReserved: # 配置 kube 資源預留cpu: 500mmemory: 1Giephemeral-storage: 1Gi systemReserved: #…