1. 层序遍历二叉树
C++ 代码
vector<vector<int> > levelTraversal(TreeNode* pRoot) { // 层序遍历二叉树
vector<vector<int> > result;
if(pRoot != NULL) {
queue<TreeNode*> q;
q.push(pRoot);
int levelWith = 0;
int n = 1;
vector<int> v;
while(!q.empty()) {
TreeNode* p = q.front();
v.push_back(p->val);
if(p->left) {
q.push(p->left);
++levelWith;
}
if(p->right) {
q.push(p->right);
++levelWith;
}
q.pop();
--n;
if(0 == n) {
result.push_back(v);
v.resize(0);
n = levelWith;
levelWith = 0;
}
}
}
return re