易错点:必须要有中序,中序中的点左右两端分别为左子树和右子树
建树时要注意函数需要返回结点
如果len值为0,需要特判返回NULL,否则会死循环
数组从0开始存储
L2-011 玩转二叉树 (中序+前序)
给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其中序遍历序列。第三行给出其前序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树反转后的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
int a[40], b[40];
struct tree{
int data;
tree* l;
tree* r;
};
tree* buildtree(int* a, int* b, int len)
{
if(len == 0) return NULL;
int i = 0;
for(i = 0; i < len; i ++ )
if(a[i] == b[0]) break;
//if(i == len) return NULL;
tree* t = new tree();
t->data = b[0];
t->l = buildtree(a, b + 1, i);
t->r = buildtree(a + i + 1, b + i + 1, len - i - 1);
return t;//容易忘记返回结点,导致段错误
}
void fceng(tree* t)
{
queue<tree*> q;
q.push(t);
while(q.size())
{
tree* temp = q.front();
q.pop();
cout << temp->data;
if(temp->r != NULL) q.push(temp->r);
if(temp->l != NULL) q.push(temp->l);
if(q.size()) cout << ' ';
}
}
int main()
{
int n;
cin >> n;
for(int i = 0; i < n; i ++ ) cin >> a[i];
for(int i = 0; i < n; i ++ ) cin >> b[i];
tree* t = buildtree(a, b, n);
fceng(t);
return 0;
}
L2-006 树的遍历 (后序+中序)
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
struct tree{
tree* l;
tree* r;
int data;
};
int n;
int a[110], b[110];
tree* buildtree(int* a, int* b, int len)
{
if(len == 0) return NULL;
int i = 0;
for(i = 0; i < len; i ++ )
if(a[len - 1] == b[i]) break;
//if(i == len) return NULL;
tree* t = new tree();
t->data = b[i];
/*a+i就得到后序遍历第一个右子树结点的地址,
b+i+1同理也是找到中序遍历中第一个结点的地址,
k-i就去掉了左子树的个数,再-1就去掉了根结点的个数*/
t->l = buildtree(a, b, i);
t->r = buildtree(a + i, b + i + 1, len - i - 1);
//把数组划分成左子树和右子树两块区域,用len和i来控制子树区间的长度
return t;
}
void ceng(tree* t)
{
queue<tree*> q;
q.push(t);
while(q.size())
{
tree* temp = q.front();
cout << temp->data;
q.pop();
if(temp->l != NULL) q.push(temp->l);
if(temp->r != NULL) q.push(temp->r);
if(q.size()) printf(" ");
}
}
int main()
{
cin >> n;
for(int i = 0; i < n; i ++ ) cin >> a[i];
for(int i = 0; i < n; i ++ ) cin >> b[i];
tree* t = buildtree(a, b, n);
ceng(t);
return 0;
}