解题思路:
解这道题的关键在于通过题目给出的前序和中序遍历的输出结构来反推二叉树的构造。这就需要我们了解前序和中序遍历的原则。
简单来说,前序就是根左右,中序就是左根右。通过他前序遍历规则我们可以知道,即使树移除了一个点(在保证树结构不被破坏的情况下,或者直接分裂成一棵新树),前序遍历的第一个输出仍然是根节点;而通过中序遍历的规则我们可以知道,根节点左边是左子树,右边是右子树。这题就是不断找根节点,将通过中序遍历输出将根节点左右分开,充当新的左子树和右子树,并将左右子树的根节点分别充当当前节点的左右结点,不会丢失数据。(字面上不太好理解,可以自己画一个图,一步步推,这样很好理解)。
查树有多少层,这里我就不讲了,这个很容易,直接递归。
下面是代码:
#include<iostream>
using namespace std;
typedef struct node {
int data;
node* left, * right;
}tree;
node* createtree(char* pre, char* in, int n)
{
int k = 0;
char* tmp;
if (n <= 0)
return NULL;
node* t;
t = (node*)malloc(sizeof(node));
t->data = *pre;
for (tmp = in; tmp < in + n; tmp++)
{
if (*tmp == *pre)
break;
}
k = tmp - in;
t->left = createtree(pre + 1, in, k);
t->right = createtree(pre + k+1, tmp+ 1, n - k - 1);
return t;
}
int height(tree* t)
{
int lchild, rchild;
if (t == NULL)
return 0;
else
{
lchild = height(t->left);
rchild = height(t->right);
return (lchild > rchild ? (lchild + 1) : (rchild + 1));
}
}
int main()
{
int n;
cin >> n;
char pre[51], in[51];
for (int i = 0; i < n; i++)
cin >> pre[i];
for (int i = 0; i < n; i++)
cin >> in[i];
tree* t;
t = createtree(pre, in, n);
int result = height(t);
cout << result;
}
运行结果:
有优化请给我留言,谢谢。