根据前序遍历和中序遍历构建二叉树


struct BinaryTreeNode
{
int m_value;
BinaryTreeNode* m_pLeftNode;
BinaryTreeNode* m_pRightNode;
};
BinaryTreeNode* ConstructCore(int* startPrerder, int* endPreorder,int* startInorder,int* endInorder)
{
//构建根节点
int rootValue = startPrerder[0];
BinaryTreeNode *rootNode = new BinaryTreeNode();
rootNode->m_value = rootValue;
rootNode->m_pLeftNode = NULL;
rootNode->m_pRightNode = NULL;
if(startPrerder == endPreorder)
{
if(startInorder == endInorder && *startPrerder == *startInorder)
{
return rootNode;
}
else
{
throw std::exception("invalid paragram");
}
}
int* rootInorder = startInorder;
//找到根节点在中序的位置
while(*rootInorder != rootValue && rootInorder <= endInorder)
{
rootInorder++;
}
if(rootInorder == endInorder && *rootInorder != rootValue)
{
throw std::exception("invalid paragram");
}
//求出左节点的个数
int leftLength = rootInorder - startInorder;
//求出新的前序遍历末节点位置，递归调用
int* leftPreorderEnd = startPrerder + leftLength;
if(leftLength > 0)
{
rootNode->m_pLeftNode = ConstructCore(startPrerder + 1,leftPreorderEnd, startInorder,rootInorder -1);

if(leftLength < endPreorder - startPrerder)
{
rootNode->m_pRightNode = ConstructCore(leftPreorderEnd + 1,endPreorder,rootInorder+1,endInorder);
}

return rootNode;
}


• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120