重建二叉树



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


#pragma once
#include<queue>
struct BTNode
{
           int value;
           BTNode* left;
           BTNode* right;
};

BTNode* ConstructCore(int * startPrevorder, int* endPreorder ,
           int* startInorder , int* endInorder)
{
           int rootValue = startPrevorder [0];
           BTNode *root = new BTNode();
          root->value = rootValue;
          root->left = root->right = NULL;
           if (startPrevorder == endPreorder)
          {
                    if (startInorder == endInorder
                             &&* startPrevorder == *startInorder )
                              return root;
                    else
                              throw std::exception ("Invalid input.");
          }
           int* rootInorder = startInorder ;
           while (rootInorder <= endInorder &&*rootInorder != rootValue)
                   ++rootInorder;
           if (rootInorder == endInorder &&*rootInorder != rootValue)
                    throw std::exception ("Invalid input.");
           int leftLength = rootInorder - startInorder ;
           int* leftPreorderEnd = startPrevorder + leftLength;
           if (leftLength > 0)
          {
                   root->left = ConstructCore( startPrevorder + 1,
                             leftPreorderEnd, startInorder, rootInorder - 1);

          }
           if (leftLength < endPreorder - startPrevorder)
          {
                   root->right = ConstructCore(leftPreorderEnd + 1,
                              endPreorder, rootInorder + 1, endInorder );
          }
           return root;
}

BTNode* Construct(int * prevorder, int* inorder , int length)
{
           if (prevorder == NULL || inorder == NULL || length <= 0)
                    return NULL ;
           return ConstructCore(prevorder , prevorder + length - 1,
                    inorder, inorder + length - 1);
}





void Test()
{
           int pre[8] = { 1, 2, 4, 7, 3, 5, 6, 8 };
           int in[8] = { 4, 7, 2, 1, 5, 3, 8, 6 };

           BTNode* root = Construct(pre, in, 8);

           //PrintTree(root);
}
  



你可能感兴趣的:(重建二叉树)