您的位置:首页 > 职场人生

面试题整理-重建二叉树

2012-10-24 15:26 357 查看
题目

根据输入的前序遍历和中序遍历。重建一棵二叉树。

解法:

其实求解很简单。关键在于求出长度。假设函数的形式如同:

template<class T>

node<T> *build(const T *pre, const T *mid, const int n);

那么pre[0]肯定是树的根,可以把中序遍历分为两部分。

一部分长度为A,另外一个长度为B。

那么pre的构成则是。pre[0]---A----B

而中序遍历的构成是:A--pre[0]---B

因此,只需要求出A与B的长度,递归重构出左子树与右子树则可。

代码如下:

#include <iostream>
#include <stack>

using namespace std;

template<class T>
struct node {
T data;
struct node<T> *left;
struct node<T> *right;
};

template<class T>
node<T> *_get_node(const T &v) {
node<T> *t = new node<T>();
if (!t) {
cerr << "Memory is not enough for _get_node()" << endl;
return NULL;
}
t->data = v;
t->left = t->right = NULL;
return t;
}

template<class T>
node<T> *build(const T *pre, const T *mid, const int n) {
if (!pre || !mid || n <= 0) return NULL;

node<T> *t = _get_node<T>(*pre);
if (1 == n) return t;

const T *me = mid - 1;
while (*++me != *pre && me < mid + n);
const int llen = me - mid;
const int rlen = n - llen - 1;

if (llen > 0) t->left = build(pre + 1, mid, llen);
if (rlen > 0) t->right = build(pre + llen + 1, mid + llen + 1, rlen);
return t;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: