原题见于 http://ac.jobdu.com/problem.php?pid=1523
-
题目描述:
-
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
-
输入:
-
输入可能包含多个测试样例,输入以EOF结束。
对于每个测试案例,输入的第一行一个整数n(1<=n<=1000, :n代表将要输入的二叉树元素的个数(节点从1开始编号)。接下来一行有n个数字,代表第i个二叉树节点的元素的值。接下来有n行,每行有一个字母Ci。
Ci=’d’表示第i个节点有两子孩子,紧接着是左孩子编号和右孩子编号。
Ci=’l’表示第i个节点有一个左孩子,紧接着是左孩子的编号。
Ci=’r’表示第i个节点有一个右孩子,紧接着是右孩子的编号。
Ci=’z’表示第i个节点没有子孩子。
-
输出:
-
对应每个测试案例,
按照从上之下,从左至右打印出二叉树节点的值。
-
样例输入:
-
7 8 6 5 7 10 9 11 d 2 5 d 3 4 z z d 6 7 z z
-
样例输出:
-
8 6 10 5 7 9 11
#include <iostream>
#include <queue>
#include <cstdlib>
using namespace std;
struct node
{
int value;
node * left;
node *right;
} ;
typedef node Node;
Node * point_node[1010];
queue<Node*> queue_Node;
void print()
{
while(!queue_Node.empty())
{
Node * BinaryNode=queue_Node.front();
queue_Node.pop();
if(BinaryNode==point_node[1])
cout<<BinaryNode->value;
else
cout<<' '<<BinaryNode->value;
if(BinaryNode->left)
{
queue_Node.push(BinaryNode->left);
}
if(BinaryNode->right)
{
queue_Node.push(BinaryNode->right);
}
}
}
void first_order(Node *root)
{
if(root==NULL)
return ;
cout<<root->value<<' ';
if(root->left!=NULL)
first_order(root->left);
if(root->right!=NULL)
first_order(root->right);
}
void mid_order(Node *root)
{
if(root==NULL)
{
return;
}
if(root->left!=NULL)
mid_order(root->left);
cout<<root->value<<' ';
if(root->right!=NULL)
mid_order(root->right);
return ;
}
int main()
{
int n;
while(cin>>n)
{
for(int i=1;i<=n;i++)
{
point_node[i]=new Node;
int key;
cin>>key;
point_node[i]->value=key;
}
char c;
int left_child,right_child;
for(int i=1;i<=n;i++)
{
cin>>c;
if(c=='d')
{
cin>>left_child>>right_child;
point_node[i]->left=point_node[left_child];
point_node[i]->right=point_node[right_child];
}
else if (c=='l')
{
cin>>left_child;
point_node[i]->left=point_node[left_child];
point_node[i]->right=NULL;
}
else if (c=='r')
{
cin>>right_child;
point_node[i]->left=NULL;
point_node[i]->right=point_node[right_child];
}
else if(c=='z')
{
point_node[i]->left=NULL;
point_node[i]->right=NULL;
}
}
/*first_order(point_node[1]);
cout<<endl;
mid_order(point_node[1]);
cout<<endl;*/
queue_Node.push(point_node[1]);
print();
cout<<endl;
}
return 0;
}