题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
http://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
第二个进入 2ms 的算法。很开心 ^_^
时间:2ms
内存:412KB
```c++
/**
- 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</int> root) {
// write code here
queue<TreeNode> q;
q.push(root);
vector<vector<int>> results;
TreeNode</int> tmp;
while(q.size()){
vector<int> data;
for(int size = q.size(); size; --size){
tmp = q.front();
if(tmp){
data.push_back(tmp->val);
q.push(tmp->left);
q.push(tmp->right);
}
q.pop();</int>
} if(data.size()) results.push_back(data); } return results; }
};