您的位置:首页 > 编程语言 > C语言/C++

【面试算法系列】已知二叉树的前序和中序遍历重建二叉树 - C语言实现

2015-09-08 17:33 841 查看
已知一二叉树的前序遍历和中序遍历重建二叉树

1. 输入前序遍历数组和中序遍历数组

2. 由前序遍历顺序可得,第一个节点是该二叉树的根节点。

3. 在中序遍历中寻找该根节点位置,该节点左边是它的左子树上的节点,右边节点是它右子树上的节点。

4. 获取该节点左边的节点数n,前序遍历除了首节点以外的前n个节点为左子树节点,后边剩下的节点为右子树上的节点。

5. 以中序遍历的根节点为分界,分为两个数组,左边重复第一步,右边也重复第一步,直到只有一个节点,则返回这个节点。

/*
* File:   main.c
* Author: Kyle
*
* Created on 2015年9月7日, 下午2:34
*/

#include <stdio.h>
#include <stdlib.h>

typedef int Item; //定义数据项类型
/*
*二叉树,结构体
*/
typedef struct btn {
Item value; //数据域
struct btn* L; //左子节点
struct btn* R; //右子节点
} BinaryTreeNode;

BinaryTreeNode* makeTree(int* a_start, int* a_end, int* b_start, int* b_end) {
//    printf("R:  %d,%d,%d,%d\n", *a_start, *a_end, *b_start, *b_end);
BinaryTreeNode *RootNode = (BinaryTreeNode *) malloc(sizeof (BinaryTreeNode));
RootNode->value = *a_start;
RootNode->L = NULL;
RootNode->R = NULL;
if (*a_start == *a_end) {//当中序跟前序一样的时候返回该节点,说明已经判断到了最后一个点
return RootNode;
}
int *i = b_start; //中序中找首节点
int leftLength = 0; //左子树的个数
while (*a_start != *i) {
++i;
//        printf("%d\n",*a_start);
++leftLength;
}
if (leftLength > 0) {
RootNode->L = makeTree(a_start + 1, a_start + leftLength, b_start, b_start + leftLength - 1);
printf("L:  %d,%d,%d,%d-----%d\n", *(a_start + 1), *(a_start + leftLength), *(b_start), *(b_start + leftLength - 1), leftLength);
}
if (i != b_end) {
RootNode->R = makeTree(a_start + leftLength + 1, a_end, i + 1, b_end);
printf("R:  %d,%d,%d,%d-----%d\n", *(a_start + leftLength + 1), *a_end, *(i + 1), *b_end);
}
return RootNode;
}

BinaryTreeNode* Construct(int* a, int a_length, int* b, int b_length) {
if (a == NULL || b == NULL || a_length < 0 || b_length < 0) {
printf("NULLl");
return NULL;
} else {
return makeTree(a, a + a_length - 1, b, b + b_length - 1);
}
}

int main() {

/**  ab分别为如下二叉树的前序遍历和中序遍历
1
*           / \
*          2   3
*         /   / \
*        4   5   6
*         \     /
*          7   8
**/
int a[] = {1, 2, 4, 7, 3, 5, 6, 8};
int b[] = {4, 7, 2, 1, 5, 3, 8, 6};
BinaryTreeNode *result = Construct(a, 8, b, 8);
printf("%d\n", result->L->value);
printf("%d\n", result->R->value);
printf("%d\n", result->L->L->value);
printf("%d\n", result->L->L->R->value);
printf("%d\n", result->R->L->value);
printf("%d\n", result->R->R->value);
printf("%d\n", result->R->R->L->value);
return (EXIT_SUCCESS);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言 面试 算法