一道和Leetcode的一道题目基本上一样的题目。
给出前序遍历和中序遍历序列,要求根据这些信息恢复一颗二叉树的原貌,然后按后序遍历序列输出。
Leetcode上有给出后序和中序,恢复二叉树的。
不过其实算法都是一样的。仿佛又回到了做Leetcode题的那段岁月中了。
还有就是输入是我特别处理过的,就两个函数,大家会了的无视,不会的可以学习下。
#include <stdio.h>
#include <string>
#include <algorithm>
using std::string;
const int MAX_B = 1024;
char buf[MAX_B];
int id = 0, len = 0;
inline char getFromBuf()
{
if (id >= len)
{
len = fread(buf, 1, MAX_B, stdin);
id = 0;
}
return buf[id++];
}
void getStrFromBuf(string &n)
{
char a = getFromBuf();
while ((a == ' ' || a == '\n') && len) a = getFromBuf();
n.clear();
while ((a != ' ' && a != '\n') && len)//老是写&&,错成||
{
n.push_back(a);
a = getFromBuf();
}
}
struct Node
{
char alpha;
Node *left, *right;
explicit Node (char a = ' ') : alpha(a), left(NULL), right(NULL) {}
};
Node *recover(string &preo, int p1, int p2, string &ino, int i1, int i2)
{
if (p1 > p2) return NULL;
Node *root = new Node(preo[p1]);
int off = 0;
for ( ; ino[i1+off] != preo[p1]; off++);
root->left = recover(preo, p1+1, p1+off, ino, i1, i1+off-1);
root->right = recover(preo, p1+off+1, p2, ino, i1+off+1, i2);
return root;
}
void releaAndPrintTree(Node *r)
{
if (r)
{
releaAndPrintTree(r->left);
releaAndPrintTree(r->right);
putchar(r->alpha);
delete r; r = NULL;
}
}
int main()
{
string preo, ino;
while (true)
{
getStrFromBuf(preo);
if (len == 0) break;
getStrFromBuf(ino);
releaAndPrintTree(recover(preo, 0, (int)preo.size()-1, ino, 0, (int)ino.size()-1));
putchar('\n');
}
return 0;
}
POJ 2255 Tree Recovery 二叉树恢复,布布扣,bubuko.com
原文地址:http://blog.csdn.net/kenden23/article/details/36879753