# 【剑指offer】面试题6：重建二叉树

（我没有用书上的代码来分析，而是用之前自己参照网上的版本写的）

typedef struct BinaryTreeNode{
int value;
BinaryTreeNode* pLeft;
BinaryTreeNode* pRight;
}BinaryTreeNode;

BinaryTreeNode* buildByPreAndIn(int* pre_order, int* in_order, int num) {
if (pre_order == NULL || in_order == NULL || num <= 0)  return NULL;

BinaryTreeNode* root = new BinaryTreeNode;
root->value = *pre_order;
root->pLeft = root->pRight = NULL;

int rootPositionInOrder = -1;
for (int i = 0; i < num; i++) {
if (in_order[i] == root->value) {
rootPositionInOrder = i;
break;
}
}

int num_Left  = rootPositionInOrder;
int num_Right = num - num_Left - 1;

int* pre_order_left  = pre_order + 1;
int* in_order_left   = in_order;
root->pLeft          = buildByPreAndIn(pre_order_left, in_order_left, num_Left);

int* pre_order_right = pre_order + num_Left + 1;
int* in_order_right  = in_order + num_Left + 1;
root->pRight         = buildByPreAndIn(pre_order_right, in_order_right, num_Right);

return root;
}

BinaryTreeNode* buildByPreAndIn(int* pre_order, int* in_order, int num);

num_Left记录左子树节点的个数；
num_Right记录右子树节点的个数；

pre_order_left记录左子树前序子数组的起始位置；
in_order_left记录左子树中序子数组的起始位置；

• 本文已收录于以下专栏：

举报原因： 您举报文章：【剑指offer】面试题6：重建二叉树 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)