1、层序打印:
用一个队列存储节点即可。需要注意的是 如何判断当前层 节点访问结束,代码中用一个int型变量存储当前层的节点数。
/*
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> >ans;
if (pRoot==nullptr)return ans;
vector<int>res;
int toBePrint = 1;
int next = 0;
queue<TreeNode* >q;
q.push(pRoot);
while(!q.empty())
{
TreeNode* tmp = q.front();
q.pop();
res.push_back(tmp->val);
toBePrint--;
if (tmp->left)
{
q.push(tmp->left);
next++;
}
if (tmp->right)
{
q.push(tmp->right);
next++;