#include <iostream>
#include <vector>
#include <string>
#include <stdlib.h>
#include <math.h>
#include <sstream>
#include <map>
#include <set>
#include <queue>
#include <algorithm>
using namespace std;
typedef struct node
{
int name;
int level;
node* left;
node* right;
node* parent;
};
int N;
queue<node*> Qn;
void bfs(node* root)
{
Qn.push(root);
while(!Qn.empty())
{
root = Qn.front();
if(root->right)
Qn.push(root->right);
if(root->left)
Qn.push(root->left);
node* temp = Qn.front();
if(Qn.size()>1)
cout<<temp->name<<" ";
else
cout<<temp->name<<endl;
Qn.pop();
}
}
void inorder(node* ptr)
{
static int cnt = 0;
if(ptr->right)
inorder(ptr->right);
cnt++;
if(cnt<N)
cout<<ptr->name<<" ";
else
cout<<ptr->name<<endl;
if(ptr->left)
inorder(ptr->left);
return;
}
int main(void)
{
cin>>N;
vector<node> tree;
node temp;
temp.name = -1;
temp.level =-1;
temp.left=NULL;
temp.right = NULL;
temp.parent = NULL;
tree.assign(N,temp);
for(int i=0;i<N;i++)
{
tree[i].name = i;
char ln,rn;
cin>>ln>>rn;
if(ln !='-')
{
int l = ln-'0';
tree[i].left = &tree[l];
tree[l].parent = &tree[i];
}
if(rn !='-')
{
int r = rn-'0';
tree[i].right = &tree[r];
tree[r].parent = &tree[i];
}
}
node* ptr = &tree[0];
while(ptr->parent)
{
ptr = ptr->parent;
}
bfs(ptr);
inorder(ptr);
return 0;
}
[PAT]1102. Invert a Binary Tree (25)
最新推荐文章于 2020-02-24 14:10:42 发布