题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
AC代码
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int> > res;
if (pRoot == NULL) {
return res;
}
queue<TreeNode*> q;
int len = 0;
q.push(pRoot);
TreeNode* node = NULL;
while (!q.empty()) {
vector<int> vec;
len = q.size();
for (int i = 0;i < len; ++i) {
node = q.front();
vec.push_back(node->val);
if (node->left) {
q.push(node->left);
}
if (node->right) {
q.push(node->right);
}
q.pop();
}
res.push_back(vec);
}
return res;
}
};
思路
关键点是找一个变量记录当前层数的结点数量.不能直接使用queue.size(),因为size会变动
网友评论