根据前序和中序遍历,构建二叉树。
前序遍历顺序是根左右,中序遍历顺序是左根右。
struct TreeNode {
int val;
TreeNode *leftChild;
TreeNode *rightChild;
};
TreeNode * buildTree(int *preOrder, int *inorder, int length) {
if(preOrder == NULL || inorder == NULL || length <= 0) {
return NULL;
}
return buildSubTree(preOrder, inorder, 0, length-1, 0, length-1);
}
/**
* 根据前序遍历[preStart, preEnd]之间的元素,和中序遍历[inStart, inEnd]之间的元素,构建子树
* preOrder 前序遍历的指针,指向第一个元素
* inorder 中序遍历的指针,指向第一个元素
* TODO 这里参数也可以传入start和end处的指针
*/
TreeNode *buildSubTree(int *preOrder, int *inorder, int preStart, int preEnd, int inStart, int inEnd) {
int headLoc = inStart;
for(; headLoc <= inEnd; ++headLoc) {
if(*(inorder+headLoc) == *(preOrder+preStart))
break;
}
if(headLoc > inEnd) {
throw std::exception("Invalid input!");
}
int preCount = headLoc - inStart; //左子树节点数量
int postCount = inEnd - headLoc; //右子树节点数量
TreeNode *head = new TreeNode();
head->val = *(preOrder+preStart);
head->leftChild = preCount == 0 ? NULL : buildSubTree(preOrder, inorder, preStart+1, preStart+preCount, inStart, headLoc-1);
head->righttChild = postCount == 0 ? NULL : buildSubTree(preOrder, inorder, preStart+preCount+1, preEnd, headLoc + 1, inEnd);
return head;
}