题目:将处于同一层的打印成一行。
方法1:
定义一个嵌套的vector(vector<vector<int>>),把处于同一层的保存在一个vector中。
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> v; //特别关键
if(pRoot==NULL)
return v;
queue<TreeNode*> q;
q.push(pRoot); //先入根节点
while(!q.empty())
{
int count=0;
int size=q.size();
vector<int> v1; //用来保存同一层节点的值
//用来对同一层的节点进行操作
while(count++<size)
{
TreeNode* t=q.front();
q.pop();
v1.push_back(t->val);
if(t->left!=NULL)
q.push(t->left);
if(t->right!=NULL)
q.push(t->right);
}
v.push_back(v1);
}
return v;
}
};
方法2:
定义两个变量,一个保存当前层未打印的节点的个数。另一个保存下一层要打印的节点的个数
#include<queue>
struct Node
{
Node(int _data)
{
data=_data;
left=NULL;
right=NULL;
}
int data;
Node* left;
Node* right;
};
void Print(Node* node)
{
if(node==NULL)
return;
queue<Node*> q;
int cur=1; //当前层节点未打印的
int next=1; //下一层节点要打印的
q.push(node);
while(!q.empty())
{
cur=next;
next=0;
while(cur-->0)
{
Node* front=q.front();
cout<<front->data<<" ";
q.pop();
if(front->left)
{
q.push(front->left);
next++;
}
if(front->right)
{
q.push(front->right);
next++;
}
}
cout<<endl;
}
}
int main()
{
Node* node1=new Node(1);
Node* node2=new Node(2);
Node* node3=new Node(3);
Node* node4=new Node(4);
Node* node5=new Node(5);
Node* node6=new Node(6);
node1->left=node2;
node1->right=node3;
node2->left=node4;
node2->right=node5;
node3->left=node6;
Print(node1);
system("pause");
return 0;
}