1102. Invert a Binary Tree (25)
2017.9.9更新
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
struct TreeNode
{
int left,right;
TreeNode(int L=-1,int R=-1):left(L),right(R){}
};
bool root[10];
int n,cnt;
vector<TreeNode> tree;
void invert(int r)
{
if(r!=-1)
{
swap(tree[r].left,tree[r].right);
invert(tree[r].left);
invert(tree[r].right);
}
}
void levtra(int r)
{
queue<int> q;
q.push(r);
while(!q.empty())
{
int s=q.front();
++cnt!=n?cout<<s<<" ":cout<<s<<endl;
q.pop();
if(tree[s].left!=-1)q.push(tree[s].left);
if(tree[s].right!=-1)q.push(tree[s].right);
}
}
void inotra(int r)
{
if(r!=-1)
{
inotra(tree[r].left);
++cnt!=n?cout<<r<<" ":cout<<r<<endl;
inotra(tree[r].right);
}
}
int main()
{
cin>>n;
tree.reserve(n);
for(int i=0;i<n;++i)
{
char lc,rc;
cin>>lc>>rc;
if(lc!='-') root[tree[i].left=lc-'0']=1;
else tree[i].left=-1;
if(rc!='-') root[tree[i].right=rc-'0']=1;
else tree[i].right=-1;
}
int r=0;
while(root[r])++r;
invert(r);
levtra(r);
cnt=0;
inotra(r);
return 0;
}
以前的ac代码
#include <stdio.h>
struct tree//树节点
{
int left,right;
}node[12];
int findroot[12];
int main()
{
int n,i;
scanf("%d",&n);
getchar();
for(i=0;i<n;++i)
{
char l,r;
scanf("%c %c",&l,&r);
getchar();
node[i].left=(l=='-')?-1:l-'0',findroot[l-'0']=1;
node[i].right=(r=='-')?-1:r-'0',findroot[r-'0']=1;
}
while(i>=0&&findroot[--i]);//找根
int root=i;
int queue[100],front=0,rear=0,s;
queue[rear++]=root;
while(front<rear)//层序遍历
{
s=queue[front++];
if(node[s].right!=-1)
queue[rear++]=node[s].right;
if(node[s].left!=-1)
queue[rear++]=node[s].left;
front==rear?printf("%d\n",s):printf("%d ",s);
}
int stack[100],top=0,c=0;
s=root;
while(s!=-1||top)//非递归中序遍历
{
while(s!=-1)
{
stack[top++]=s;
s=node[s].right;
}
if(top)
{
s=stack[--top];
++c;
c==n?printf("%d",s):printf("%d ",s);
s=node[s].left;
}
}
return 0;
}