结点结构
typedef struct Node{
char data;
struct Node *left;
struct Node *right;
}Node;
已知前序和中序遍历顺序,建立二叉树
![]() | ![]() |
问题的关键在于如何把前序和中序划分出左右子树。
- 前序提供根节点
pre[pre_start]
, - 通过
find()
函数在中序中找到根节点位置mid_root_pos
,左边即为左子树,从而得到左子树长度left_len
。
int find(char str[], char x, int start, int end){
for(int k = start; k < end; k++){
if(str[k] == x)
return k;
}
return -1;
}
Node* CreateFrom(char pre[], char mid[], int pre_start, int pre_end, int mid_start, int mid_end){
if(pre_start >= pre_end || mid_start >= mid_end)
return NULL;
else if(pre_start + 1 == pre_end && mid_start + 1 == mid_end && pre[pre_start] == mid[mid_start]){
Node* p = (Node*)malloc(sizeof(Node));
p->data = pre[pre_start];
p->left = NULL;
p->right = NULL;
return p;
}
else{
char root_data = pre[pre_start];
int mid_root_pos = find(mid, root_data, mid_start, mid_end);
int left_len = mid_root_pos - mid_start;
int right_len = mid_end - left_len - 1;
Node* root = (Node*)malloc(sizeof(Node));
Node* left = CreateFrom(pre, mid, pre_start + 1, pre_start + left_len + 1, mid_start, mid_root_pos);
Node* right= CreateFrom(pre, mid, pre_start + left_len + 1, pre_end, mid_root_pos + 1, mid_end);
root->data = root_data;
root->left = left;
root->right = right;
return root;
}
}