剑指offer:重建二叉树

题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列为{1,2,4,7,3,5,6,8}和中序遍历的序列{4,7,2,1,5,3,8,6},则重建出下图所示的二叉树并输出它的头结点。


分析:前序遍历的第一个元素就是根节点的值
  1. BinaryTreeNode* Construct(int* preorder, int* inorder, int length)
  2. {
  3. if(preorder == NULL || inorder == NULL || length <= 0)
  4. return NULL;
  5. return ConstructCore(preorder, preorder + length - 1,
  6. inorder, inorder + length - 1);
  7. }
  8. BinaryTreeNode* ConstructCore
  9. (
  10. int* startPreorder, int* endPreorder,
  11. int* startInorder, int* endInorder
  12. )
  13. {
  14. // 前序遍历序列的第一个数字是根结点的值
  15. int rootValue = startPreorder[0];
  16. BinaryTreeNode* root = new BinaryTreeNode();
  17. root->m_nValue = rootValue;
  18. root->m_pLeft = root->m_pRight = NULL;
  19. if(startPreorder == endPreorder)
  20. {
  21. if(startInorder == endInorder && *startPreorder == *startInorder)
  22. return root;
  23. else
  24. throw std::exception("Invalid input.");
  25. }
  26. // 在中序遍历中找到根结点的值
  27. int* rootInorder = startInorder;
  28. while(rootInorder <= endInorder && *rootInorder != rootValue)
  29. ++ rootInorder;
  30. if(rootInorder == endInorder && *rootInorder != rootValue)
  31. throw std::exception("Invalid input.");
  32. int leftLength = rootInorder - startInorder;
  33. int* leftPreorderEnd = startPreorder + leftLength;
  34. if(leftLength > 0)
  35. {
  36. // 构建左子树
  37. root->m_pLeft = ConstructCore(startPreorder + 1, leftPreorderEnd,
  38. startInorder, rootInorder - 1);
  39. }
  40. if(leftLength < endPreorder - startPreorder)
  41. {
  42. // 构建右子树
  43. root->m_pRight = ConstructCore(leftPreorderEnd + 1, endPreorder,
  44. rootInorder + 1, endInorder);
  45. }
  46. return root;
  47. }





posted @ 2015-07-21 10:02  Lucas_1993  阅读(306)  评论(0编辑  收藏  举报