中序和前序或后序序列还原二叉树
设计说明
已知:可以通过中序遍历与前序遍历或中序遍历与后序遍历还原一颗二叉树;但并未研究为何前序与后序不能还原,且还原出来的情况会有许多种
现前序和中序、后序和中序的还原代码如下:
# include <iostream>
# include <stdlib.h>
using namespace std;
typedef char elementType;
struct Node
{
elementType data;
Node* left;
Node* right;
};
int indexOf(string str, char ch)
{
for (int i = 0; i < str.length(); i++)
{
if (str[i] == ch)
{
return i;
}
}
return -1;
}
Node* restoreTreeByPreAndInOrder(string preOrderStr, string inOrderStr)
{
if (preOrderStr.length() == 0)
{
return NULL;
}
Node* cur = (Node*)malloc(sizeof(Node));
if (cur == NULL)
{
cout << "内存分配失败" << endl;
return NULL;
}
cur->data = (elementType)preOrderStr[0];
int indexOfNewRoot = indexOf(inOrderStr, preOrderStr[0]);
if (indexOfNewRoot == -1)
{
return NULL;
}
cur->left = restoreTreeByPreAndInOrder(preOrderStr.substr(1, indexOfNewRoot), inOrderStr.substr(0, indexOfNewRoot));
cur->right = restoreTreeByPreAndInOrder(preOrderStr.substr(indexOfNewRoot + 1), inOrderStr.substr(indexOfNewRoot + 1));
return cur;
}
Node* restoreTreeByPostAndInOrder(string postOrderStr, string inOrderStr)
{
int length = postOrderStr.length();
if (length == 0)
{
return NULL;
}
Node* cur = (Node*)malloc(sizeof(Node));
if (cur == NULL)
{
cout << "内存分配失败" << endl;
return NULL;
}
cur->data = (elementType)postOrderStr[length - 1];
int indexOfNewRoot = indexOf(inOrderStr, postOrderStr[length - 1]);
if (indexOfNewRoot == -1)
{
return NULL;
}
cur->left = restoreTreeByPostAndInOrder(postOrderStr.substr(0, indexOfNewRoot), inOrderStr.substr(0, indexOfNewRoot));
cur->right = restoreTreeByPostAndInOrder(postOrderStr.substr(indexOfNewRoot, length - indexOfNewRoot - 1),
inOrderStr.substr(indexOfNewRoot + 1));
return cur;
}
void preOrder(Node* root)
{
if (root == NULL)
{
return;
}
cout << root->data << " ";
preOrder(root->left);
preOrder(root->right);
}
void inOrder(Node* root)
{
if (root == NULL)
{
return;
}
inOrder(root->left);
cout << root->data << " ";
inOrder(root->right);
}
void postOrder(Node* root)
{
if (root == NULL)
{
return;
}
postOrder(root->left);
postOrder(root->right);
cout << root->data << " ";
}
int main()
{
string preOrderStr = "ABCDEFGHIJ";
string inOrderStr = "BDCEAGIJHF";
Node* root = restoreTreeByPreAndInOrder(preOrderStr, inOrderStr);
preOrder(root);
cout << endl << "************************************" << endl;
inOrder(root);
cout << endl << "************************************" << endl;
string postOrderStr = "DECBJIHGFA";
Node* root2 = restoreTreeByPostAndInOrder(postOrderStr, inOrderStr);
preOrder(root2);
cout << endl << "************************************" << endl;
postOrder(root2);
}