您的位置:首页 > 其它

根据二叉树的前序遍历和中序遍历结果重建出该二叉树

2014-04-03 10:35 246 查看
struct BinaryTreeNode{

   int m_nValue;

   BinaryTreeNode* m_nLeft;

   BinaryTreeNode* m_nRight;

};

BinaryTreeNode* Construct(int* preorder,int* inorder,int length){

   if(preorder=NULL||inorder=NULL||length<=0)

   return NULL;

    return ConstructCore(preorder,preorder+length-1,inorder,inorder+length-1);

}

BinaryTreeNode* ConstructCore(int* startPreorder,int* endPreorder,int* startInorder,int* endInorder){

   int rootValue=startPreorder[0]; //第一个值为根节点

   BinaryTreeNode* root=new BinaryTreeNode();

   root->m_nValue=rootValue;

   root->m_nLeft=root->m_nRight=NULL; //构建节点

   if(startPreorder=endPreorder){

   if(startInorder=endInorder&&*startPreorder=*startInorder) //只有一个结点的时候

   return root;

   else

   throw exception("Invalid Input");

}

 int* rootInorder=startInorder;

   while(rootInorder<=endInorder&&*rootInorder!=rootValue) //在中序遍历中找到根节点

   ++rootInorder;

   if(rootInorder==endInorder&&*rootInorder!=rootValue) //找到最后一点也不是要找的值则输入有误

   throw exception("Invalid Input");

   int leftLength=rootInorder-startInorder;

   int* leftPreorderEnd=startPreorder+leftLength;

   if(leftLength>0){

   root->m_nLeft=ConstructCore(startPreorder+1,leftPreorderEnd,startInorder,rootInorder-1);

}

 if(leftLenth<endPreorder-startPreorder)

root->m_nRight=ConstructCore(leftPreorderEnd+1,endPreorder,rootInorder+1,endInorder);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树
相关文章推荐