struct Node{
char val;
Node* left;
Node* right;
Node(char a): val(a), left(NULL), right(NULL){}
};
void buildBinaryTreeAccordingPreAndInOrder(string preOrder, string inOrder, int length, Node* &head){
if(length<1) return ;
char data = preOrder[0];
Node* tempPoint = new Node(data);
head = tempPoint;
int indexOfInOrder = (int)inOrder.find(data);
string leftInOrder = inOrder.substr(0, indexOfInOrder);
string rightInOrder = inOrder.substr(indexOfInOrder+1);
string leftPreOrder = preOrder.substr(1, indexOfInOrder);
string rightPreOrder = preOrder.substr(indexOfInOrder+1);
buildBinaryTreeAccordingPreAndInOrder(leftPreOrder, leftInOrder, indexOfInOrder, head->left);
buildBinaryTreeAccordingPreAndInOrder(rightPreOrder, rightInOrder, length-indexOfInOrder-1, head->right);
}
最后編輯于 :
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者