#include<stdio.h> //为什么按照之前的题的思路,无法解决
#include<stdlib.h>
int a[100];
int b[100];
typedef struct Node* Tree;
struct Node{
int data;
Tree left;
Tree right;
};
void print(Tree p);
Tree createNode();
Tree buildTree(int a1, int a2, int b1, int b2);
int getHeight(Tree head);
int main(){
int n;
scanf("%d", &n);
for(int i = 0; i < n; i++){
scanf("%d", &a[i]);
}
for(int i = 0; i < n; i++){
scanf("%d", &b[i]);
}
Tree root = buildTree(0, n - 1, 0, n - 1);
//printf("%d", getHeight(root));
print(root);
return 0;
}
Tree createNode(){
Tree node = (Tree)malloc(sizeof(struct Node));
node->left = NULL;
node->right = NULL;
return node;
}
Tree buildTree(int a1, int a2, int b1, int b2){
if(a1 > a2) return NULL;
Tree root = createNode();
root->data = a[a2];
int num = 0;
for(int i = b1; i <= b2; i++){
num = i - b1;
if(b[i] == a[a2]){
if(i != b1){
root->left = buildTree(a1, a2 - b2 + i + num-1, b1, i - 1);
}
if(i != b2){
root->right = buildTree(a2 - b2 + i, a2 - 1, i + 1, b2);
}
}
}
return root;
}
int getHeight(Tree head){
if (head == NULL) return 0;
int leftHeight = getHeight(head->left);
int rightHeight = getHeight(head->right);
return (leftHeight > rightHeight) ? leftHeight + 1 : rightHeight + 1;
}
void print(Tree p){
if(p){
printf("%d ",p->data);}
print(p->left);
print(p->right);
}
希望大神能帮忙看看,已知后序和中序怎样建一棵二叉树
最新推荐文章于 2024-12-13 21:39:38 发布