日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

[LeetCode] Binary Tree Level Order Traversal 二叉树层次遍历(DFS | BFS)

發布時間:2024/5/28 编程问答 48 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [LeetCode] Binary Tree Level Order Traversal 二叉树层次遍历(DFS | BFS) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

目錄:
1.Binary Tree Level Order Traversal - 二叉樹層次遍歷 BFS
2.Binary Tree Level Order Traversal II - 二叉樹層次遍歷從低往高輸出 BFS
3.Maximum Depth of Binary Tree - 求二叉樹的深度 DFS
4.Balanced Binary Tree - 判斷平衡二叉樹 DFS
5.Path Sum - 二叉樹路徑求和判斷DFS


題目概述:
Given a binary tree, return the?level order?traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree?{3,9,20,#,#,15,7},

3/ \9 20/ \15 7

return its level order traversal as:

[[3],[9,20],[15,7] ]

Here's an example:

1/ \2 3/4\5 The above binary tree is serialized as?"{1,2,3,#,#,4,#,#,5}".


題目分析:
? ? ? ? 本題考查的就是二叉樹的層次遍歷,需要注意的是二叉樹用數組的表示方法,二叉樹的每層是從左到右存入數組的。方法包括:
? ? ? ? 1.層次遍歷。二維數組存儲數字和深度,輸出二維數組即可,過于復雜。
? ? ? ? 2.通過隊列BFS廣度優先搜索。
? ? ? ? 3.通過DFS深度優先搜索實現。

我的代碼:

/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/ class Solution { public://二叉樹層次遍歷 通過隊列BFS廣度優先搜索vector<vector<int>> levelOrder(TreeNode* root) {vector<vector<int>> result;queue<TreeNode*>q; vector<int> level; //每層結果int size,i;TreeNode* p;if(root==NULL) return result;q.push(root); //入隊while(!q.empty()) {//隊列中有幾個元素就依次遍歷每個元素的左右結點level.clear();size=q.size();for(i=0; i<size; i++) {p=q.front(); //隊首元素值賦給pq.pop(); //出隊level.push_back(p->val);if(p->left) { //依次壓入左右結點元素q.push(p->left);}if(p->right) {q.push(p->right);}}result.push_back(level); //添加每層數據}return result;} };


代碼詳解:
? ? ? ? 該題目你如果采用C語言二維數組過于復雜,故采用C++的容器vector實現。同時BFS廣度優先搜索采用隊列queue實現,常見方法如下(參考地址):
? ? ? ? 1.棧操作

#include<stack> 頭文件 stack<int> s 定義棧 s.empty() 如果棧為空返回true,否則返回false s.size() 返回棧中元素的個數 s.pop() 刪除棧頂元素但不返回其值 s.top() 返回棧頂的元素,但不刪除該元素 s.push() 在棧頂壓入新元素 ? ? ? ? 2.隊列操作
#include<queue> 頭文件 queue<int> q 定義隊列 q.empty() 如果隊列為空返回true,否則返回false q.size() 返回隊列中元素的個數 q.pop() 刪除隊列首元素但不返回其值 q.front() 返回隊首元素的值,但不刪除該元素 q.push() 在隊尾壓入新元素 q.back() 返回隊列尾元素的值,但不刪除該元素 ? ? ? ? 3.二叉樹層次遍歷如何使用隊列
? ? ? ? 由于二叉樹是從左至右進行輸入,故層次遍歷通過隊列存儲每層的結點,它存儲的順序也是前一個結點的左孩子結點、右孩子結點,依次順序進出隊列。

? ? ? ? DFS代碼參考地址:LeetCode Binary Tree Level Order Traversal


其他題目:
Binary Tree Level Order Traversal II
? ? ? ? 層次遍歷從低往root結點輸出,如?
Given binary tree?{3,9,20,#,#,15,7},

3/ \9 20/ \15 7

? ? ? ? ? return its level order traversal as:

[[15,7],[9,20],[3] ] ? ? ? ? 最簡單方法通過層次遍歷BFS調用隊列后逆序倒置vector容器即可。
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/ class Solution { public:vector<vector<int>> levelOrderBottom(TreeNode* root) {vector<vector<int>> result;vector<int> level;queue<TreeNode*> q;if(root==NULL)return result;q.push(root);while(!q.empty()) {//層次遍歷level.clear();int size=q.size();for(int i=0; i<size; i++) { //注意:不能i<q.size() 當入隊時它會變換TreeNode* p=q.front();q.pop();level.push_back(p->val);if(p->left)q.push(p->left);if(p->right)q.push(p->right);}//每層結果存入容器result.push_back(level);}/** 逆序輸出 倒置容器調用函數* reverse(result.begin(),result.end());* return result;*/vector<vector<int>>::iterator iter; //迭代器vector<vector<int>> res;for(iter=result.end()-1; iter!=result.begin()-1; iter--){level.clear();for(int i=0; i<(*iter).size(); i++) //復制每層內容{level.push_back((*iter)[i]);}res.push_back(level);}return res;} };? ? ? ? PS:如果是每層的也要逆序的話,就把left 和right 入隊的順序調換一下。另一種遍歷方法參考:http://www.cnblogs.com/ganganloveu/p/3843470.html
? ? ? ??


Maximum Depth of Binary Tree - 求二叉樹的深度
? ? ? ? 常見方法通過BFS層次遍歷計算二叉樹層數及深度或通過DFS計算二叉樹從root到leaf結點最長路徑及深度,在采用BSF代碼中可通過前面代碼進行修改,但錯誤:
? ? ? ? ? ? ? ? ? ? ? ? [0,2,4,1,null,3,-1,5,1,null,6,null,8] output=5 Excepted=4
? ? ? ? 故采用DFS進行深度遞歸搜索。代碼如下: int maxDepth(struct TreeNode* root) {if(root == NULL) return 0;int left = maxDepth(root->left);int right = maxDepth(root->right);return (left >= right ? left : right) + 1; } ? ? ? ? BFS代碼參考:http://blog.csdn.net/sunbaigui/article/details/8980887



Balanced Binary Tree - 判斷平衡二叉樹
? ? ? ? 平衡二叉樹是一 棵空樹或它的左右兩個子樹的高度差的絕對值不超過1,并且左右兩個子樹都是一棵平衡二叉樹。參考前面的計算深度方法完成。

int DFS(struct TreeNode* p) {if(p==NULL)return 0;int left=DFS(p->left);int right=DFS(p->right);return (left>=right?left:right)+1;} //遞歸判斷左右子樹結點是否符合平衡二叉樹 bool isBalancedNode(struct TreeNode* L,struct TreeNode* R) {if(!L&&!R) return true;//自定義DFS函數計算結點的深度int left=DFS(L);int right=DFS(R);//平衡二叉樹左右結點深度相差0或1if(abs(left-right)>1) return false;else if(L&&R) //必須存在 否則會報錯RE [1,2]時R->left不存在return isBalancedNode(L->left,L->right) && isBalancedNode(R->left,R->right); } bool isBalanced(struct TreeNode* root) {if(root==NULL)return true;if(root&&!root->left&&!root->right)return true;else return isBalancedNode(root->left,root->right); } ? ? ? ? 另一種方法參考地址,也可通過后序遍歷實現。
/*** Definition for binary tree* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/ class Solution { public:bool checkBalance(TreeNode *node, int &dep){if (node == NULL){dep = 0;return true;}int leftDep, rightDep;bool leftBalance = checkBalance(node->left, leftDep);bool rightBalance = checkBalance(node->right, rightDep);dep = max(leftDep, rightDep)+1;return leftBalance && rightBalance && (abs(rightDep - leftDep) <= 1);}bool isBalanced(TreeNode *root) {int dep;return checkBalance(root, dep);} };


Path Sum - 二叉樹路徑求和判斷

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.For example:
Given the below binary tree and?sum = 22,

5/ \4 8/ / \11 13 4/ \ \7 2 1

return true, as there exist a root-to-leaf path?5->4->11->2?which sum is 22.

? ? ? ? 該題主要考察DFS或BFS計算root到leaf結點路徑求和是否存在一條與sum相等的path。我采用DFS結合計算二叉樹深度完成,最初打算自定義isNode(*root,num)函數判斷,后來直接通過判斷每個結點是否是leaf且值為sum-前面結點。代碼如下:
/*** Definition for a binary tree node.* struct TreeNode {* int val;* struct TreeNode *left;* struct TreeNode *right;* };*///思路:通過DFS計算root-to-leaf的結果 bool hasPathSum(struct TreeNode* root, int sum) {if(root==NULL)return false;else if(root&&!root->left&&!root->right&&root->val==sum) //僅root結點return true;else if(root&&!root->left&&!root->right&&root->val!=sum)return false;else //包括子結點return hasPathSum(root->left,(sum - root->val)) ||hasPathSum(root->right,(sum - root->val)); }


(By:Eastmount 2015-9-11 凌晨3點半? ?http://blog.csdn.net/eastmount/)

總結

以上是生活随笔為你收集整理的[LeetCode] Binary Tree Level Order Traversal 二叉树层次遍历(DFS | BFS)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。