上面是编程之美上的解法,下面是自己的解法:
#include <iostream>
#include <queue>
using namespace std;
struct Node
{
Node(int i = -1, Node *pLeft = NULL, Node *pRight = NULL) : data(i), left(pLeft), right(pRight) {}
int data;
Node *left;
Node *right;
};
const char *preOrder = "12473568";
const char *inOrder = "47215386";
void printLevel(Node *root)
{
if (root == NULL)
return;
queue<Node *> nqueue;
nqueue.push(root);
int start = 0;
int last = 1;
int tempLast = last;
while (!nqueue.empty())
{
Node *top = nqueue.front();
nqueue.pop();
cout << top->data << " ";
if (top->left)
{
nqueue.push(top->left);
last++;
}
if (top->right)
{
nqueue.push(top->right);
last++;
}
start++;
if (start == tempLast)
{
tempLast = last;
cout << endl;
}
}
}
Node *_construct(const char *preOrder, const int preLength,
const char *inOrder, const int inLength)
{
if (preOrder == NULL || preLength <= 0 || inOrder == NULL || inLength <= 0)
return NULL;
int pos = inLength;
for (int i = 0; i < inLength; i++)
{
if (inOrder[i] == *preOrder)
{
pos = i;
break;
}
}
if (pos == inLength)
{
cout << "wrong" << endl;
return NULL;
}
cout << *preOrder << " ";
Node *newNode = new Node(*preOrder - '0');
newNode->left = _construct(preOrder + 1, preLength - 1, inOrder, pos);
newNode->right = _construct(preOrder + pos + 1, preLength - 1, inOrder + pos + 1, inLength - pos - 1);
return newNode;
}
Node *construct(const char *preOrder, const char *inOrder)
{
if (preOrder == NULL || inOrder == NULL)
return NULL;
int preLength = strlen(preOrder);
int inLength = strlen(inOrder);
return _construct(preOrder, preLength, inOrder, inLength);
}
void preTranverse(Node *root)
{
if (root == NULL)
return;
cout << root->data << " ";
preTranverse(root->left);
preTranverse(root->right);
}
void main()
{
Node *root = construct(preOrder, inOrder);
cout << endl;
if (root != NULL)
{
preTranverse(root);
}
else
{
cout << "wrong" << endl;
}
}
289

被折叠的 条评论
为什么被折叠?



