題目要求:二叉樹的層序周遊,給出一棵樹,傳回一個存儲着數組的數組v,每個層的節點組成一個數組,所有層的節點數組組成v。
解題方法:用兩個隊列來實作,一個隊列用來存儲上一層的節點,另一個隊列用來存儲下一層的節點。
/**
* 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>> levelOrder(TreeNode* root) {
vector<vector<int>> v;
if(root==NULL)
return v;
queue<TreeNode*> q1,q2;
TreeNode* tem=root;
q1.push(tem);
while(!q1.empty()){
vector<int> t;
while(!q1.empty()){
tem=q1.front();
q1.pop();
t.push_back(tem->val);
if(tem->left)
q2.push(tem->left);
if(tem->right)
q2.push(tem->right);
}
v.push_back(t);
q1=q2;
while(!q2.empty()){
q2.pop();
}
}
return v;
}
};