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

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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值