①先处理传入的数组,如果数组没问题了,正式开始根据两个数组构建树
BitTree Construct(char *preorder, char *inorder, int len) {
if (preorder==nullptr || inorder==nullptr || len < 0)
return nullptr;
return ConstructCore(preorder, preorder + len - 1, inorder, inorder + len - 1);
}
②传入先序遍历数组的首尾指针和中序遍历的首尾指针
BitTree ConstructCore(char *preorderbegin, char *preorderend, char *inorderbegin, char *inorderend) {
int rootValue = preorderbegin[0];
BitTree root = (BitTree)malloc(sizeof(BitNode));
root->data = rootValue;
root->left = nullptr;
root->right = nullptr;//构建树的节点
if (preorderbegin == preorderend) {
if (inorderbegin == inorderend&&*preorderbegin == *preorderend)//这里没搞懂①
return root;
else
throw std::exception("Invalid input");
}
char* rootInorder = inorderbegin;
while (rootInorder <= inorderend&&*rootInorder != rootValue)
++rootInorder;
if(rootInorder==inorderend&&*rootInorder!=rootValue)
throw std::exception("Invalid input");
int leftlen = rootInorder - inorderbegin;
char *leftPreorderEnd = preorderbegin + leftlen;
if (leftlen > 0) {
root->left = ConstructCore(preorderbegin + 1, leftPreorderEnd, inorderbegin, rootInorder - 1);
}
if (leftlen < preorderend - preorderbegin)
root->right = ConstructCore(leftPreorderEnd + 1, preorderend, rootInorder + 1, inorderend);
return root;
}