面试题整理-重建二叉树
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的长度,递归重构出左子树与右子树则可。
代码如下:
根据输入的前序遍历和中序遍历。重建一棵二叉树。
解法:
其实求解很简单。关键在于求出长度。假设函数的形式如同:
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; }
相关文章推荐
- 【剑指offer】面试题7:重建二叉树
- 剑指offer 面试题6 重建二叉树
- 剑指Offer面试题6[重建二叉树]
- 剑指offer面试题6 重建二叉树(java)
- 剑指offer面试题6:重建二叉树
- 面试题-前序中序序列重建二叉树
- 剑指offer-chapter2-面试题6-重建二叉树(java)
- 面试题6:重建二叉树
- 面试题6:重建二叉树
- 面试题6- 重建二叉树
- 【剑指offer】面试题6:重建二叉树
- 剑指Offer面试题:5.重建二叉树
- 剑指Offer:面试题6——重建二叉树(java实现)
- 剑指offer面试题6:重建二叉树
- 剑指offer面试题06:重建二叉树
- 剑指offer|面试题6:重建二叉树(Java实现)
- 剑指Offer----面试题六:重建二叉树
- 剑指offer-面试题06-重建二叉树
- 剑指offer-->面试题6 重建二叉树
- 面试题6:重建二叉树