题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
http://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
使用队列求解
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @return int整型vector<vector<>>
*/
vector<vector<int> > levelOrder(TreeNode* root) {
// write code here
vector<vector<int>> res;
queue<TreeNode*> levelNode;
int cnt = 0;
if(root != NULL){
levelNode.push(root);
cnt = 1;
}
while(levelNode.size() != 0){
int cntTmp = 0;
vector<int> level;
for(int i=0; i<cnt; i++){
TreeNode* treeNode = levelNode.front();
level.push_back(treeNode->val);
if(treeNode->left != NULL){
levelNode.push(treeNode->left);
cntTmp++;
}
if(treeNode->right != NULL){
levelNode.push(treeNode->right);
cntTmp++;
}
levelNode.pop();
}
cnt = cntTmp;
res.push_back(level);
}
return res;
}
};