玩转二叉树
给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其中序遍历序列。第三行给出其前序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树反转后的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7
1 2 3 4 5 6 7
4 1 3 2 6 5 7
输出样例:
4 6 1 7 5 3 2
题解:
根据前序+中序建立二叉树
步骤
只要满足中序左节点在右节点的左边,重复:
根节点的值等于后序的最左节点的值
中序中找到根节点的位置,此时的根节点把树分为左右两部分
根据中序确定前序中的左子树和右子树两部分的点的个数
建立此根节点的左右子树
返回建好的根节点
否则返回NULL
坑点:
镜面,就是要求遍历输出的时候先右再左
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int n;
int pre[35];
int in[35];
typedef struct node
{
int data;
struct node * left;
struct node * right;
}Node;
/*
1 2 3 4 5 6 7 in
4 1 3 2 6 5 7 pre
*/
Node * create(int inL,int inR,int preL,int preR)
{
if(inL>inR)
return NULL;
Node * root =new Node();
root->data=pre[preL];
int num;
for(int i=inL;i<=inR;i++)
{
if(in[i]==pre[preL])
{
num=i;
break;
}
}
num-=inL;
root->left=create(inL,inL+num-1,preL+1,preL+num);
root->right=create(inL+num+1,inR,preL+1+num,preR);
return root;
}
void bfs(Node *root)
{
queue<Node*>q;
q.push(root);
cout<<root->data;
while(!q.empty())
{
Node * tp=q.front();
q.pop();
if(tp->right!=NULL)
{
q.push(tp->right);
cout<<" "<<tp->right->data;
}
if(tp->left!=NULL)
{
q.push(tp->left);
cout<<" "<<tp->left->data;
}
}
}
int main(void)
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n;
for(int i=0;i<n;i++)
cin>>in[i];
for(int i=0;i<n;i++)
cin>>pre[i];
Node * root=create(0,n-1,0,n-1);
bfs(root);
return 0;
}