Binary Tree Level Order Traversal
使用两个队列
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
vector<vector<int>> res;
public:
vector<vector<int> > levelOrder(TreeNode *root) {
if (root==NULL) {
return res;
}
queue<TreeNode*> curQ,nextQ;
curQ.push(root);
while (!curQ.empty()) {
vector<int> layerRes;
while (!curQ.empty()) {
TreeNode *tmp=curQ.front();
layerRes.push_back(tmp->val);
curQ.pop();
if (tmp->left!=NULL) {
nextQ.push(tmp->left);
}
if (tmp->right!=NULL) {
nextQ.push(tmp->right);
}
}
curQ=nextQ;
while (!nextQ.empty()) {//清空
nextQ.pop();
}
res.push_back(layerRes);
}
return res;
}
};
参考: