[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},
return its level order traversal as:
[[3],[9,20],[15,7] ] Here's an example:
題目分析:
? ? ? ? 本題考查的就是二叉樹的層次遍歷,需要注意的是二叉樹用數組的表示方法,二叉樹的每層是從左到右存入數組的。方法包括:
? ? ? ? 1.層次遍歷。二維數組存儲數字和深度,輸出二維數組即可,過于復雜。
? ? ? ? 2.通過隊列BFS廣度優先搜索。
? ? ? ? 3.通過DFS深度優先搜索實現。
我的代碼:
代碼詳解:
? ? ? ? 該題目你如果采用C語言二維數組過于復雜,故采用C++的容器vector實現。同時BFS廣度優先搜索采用隊列queue實現,常見方法如下(參考地址):
? ? ? ? 1.棧操作
#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},
? ? ? ? ? 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,并且左右兩個子樹都是一棵平衡二叉樹。參考前面的計算深度方法完成。
/*** 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,
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)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [LeetCode] Remove Du
- 下一篇: [LeetCode] Invert Bi