剑指offer面试题6:重建二叉树

来源:互联网 发布:单片机培训网 编辑:程序博客网 时间:2024/06/03 19:55

题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树,输出头结点。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

struct BinaryTreeNode{    int m_nValue;    BinaryTreeNode* m_pLeft;    BinaryTreeNode* m_pRight;}
#include <exception>#include <iostream>#include <vector>using namespace std;struct BinaryTreeNode {  int m_nValue;  BinaryTreeNode *m_pLeft;  BinaryTreeNode *m_pRight;};BinaryTreeNode *construct(const vector<int> &forward, int fs, int fe,                          const vector<int> &midward, int ms, int me) {  //头结点为第一个元素  BinaryTreeNode *head = new BinaryTreeNode;  head->m_nValue = forward[fs];  head->m_pLeft = head->m_pRight = NULL;  if (fs == fe && ms == me)    return head;  //在中序遍历中找到根节点  int mid = ms;  while (mid < me && midward[mid] != forward[fs])    ++mid;  int leftfe = fs + mid - ms;  if (mid > ms)    head->m_pLeft = construct(forward, fs + 1, leftfe, midward, ms, mid - 1);  if (mid < me)    head->m_pRight = construct(forward, leftfe + 1, fe, midward, mid + 1, me);  return head;}BinaryTreeNode *Reconstruct(const vector<int> &forward,                            const vector<int> &midward) {  if (forward.empty() || midward.empty())    return NULL;  return construct(forward, 0, forward.size() - 1, midward, 0,                   midward.size() - 1);}void printlist(BinaryTreeNode *head) {  if (head == NULL)    return;  cout << head->m_nValue << " ";  printlist(head->m_pLeft);  printlist(head->m_pRight);}int main(int argc, char const *argv[]) {  int ia[] = {1, 2, 4, 7, 3, 5, 6, 8};  vector<int> forward(ia, ia + 8);  int ib[] = {4, 7, 2, 1, 5, 3, 8, 6};  vector<int> midward(ib, ib + 8);  BinaryTreeNode *head = Reconstruct(forward, midward);  printlist(head);  return 0;}
0 0
原创粉丝点击