Binary Tree Level Order Traversal(二叉樹層序遍歷-儲存並返回結果集)
阿新 • • 發佈:2019-01-09
題目描述
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:
confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.
OJ’s Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where ‘#’ signifies a path terminator where no node exists below.
Here’s an example:
The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".
題目大意
層序遍歷二叉樹
把遍歷結果儲存在一個二維陣列中
一層儲存在二維陣列的一行中
思路
剛開始用的時候感覺vector不好用,現在越用感覺越好用
用佇列實現二叉樹的層序遍歷
關鍵是定義兩個指標,指向每一層的當前結點和最後一個結點
每當一層遍歷完畢,層數加一,並且給vector二維陣列增加新的一行。
程式碼
#include<iostream> #include<vector> #include<queue> using namespace std; /* 結構體定義 */ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; /* 具體實現演算法 */ typedef TreeNode* tree; vector<vector<int> > levelOrder(TreeNode *root) { vector<vector<int > > vec; // 定義二維陣列,其中元素為int型別 if(root == NULL)return vec; queue<tree> qu; // 儲存二叉樹層序遍歷結點的指標 qu.push(root); tree now = root; // 當前結點指標 tree last = root; // 儲存每層最後一個結點的指標 int lev = 0; // 儲存層的序號 vector<int> vt; // 二維陣列的新一行 vec.push_back(vt); // 給二維陣列加一行 while(!qu.empty()) { now = qu.front(); qu.pop(); vec[lev].push_back(now->val); if(now->left != NULL)qu.push(now->left); if(now->right != NULL)qu.push(now->right); if(last==now && !qu.empty()) { // 表示當前層已遍歷完畢 lev++; // 層數序號加一 last = qu.back(); // last指向新的一層的最後一個元素 vec.push_back(vt); // 給二維陣列加一行 } } return vec; } // 二叉樹的層序遍歷演算法 void print(TreeNode *root) { queue<tree > qu; qu.push(root); while(!qu.empty()) { tree now = qu.front(); qu.pop(); cout<<now->val<<endl; if(now->left != NULL)qu.push(now->left); if(now->right != NULL)qu.push(now->right); } } int main() { tree tr; tr = new TreeNode(1); tree t1; t1 = new TreeNode(2); tr->left = t1; tree t2; t2 = new TreeNode(3); tr->right = t2; tree t3; t3 = new TreeNode(4); t2->left = t3; vector<vector<int > > vec; //print(tr); vec = levelOrder(tr); for(int i=0; i<vec.size(); i++) { for(int j=0; j<vec[i].size(); j++) { cout<<vec[i][j]<<' '; } cout<<endl; } return 0; }
執行結果
以上。