您的位置:首页 > 其它

已知中序和前序序列建二叉树

2012-04-21 18:23 225 查看
#include<iostream>
using namespace std;

struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode * m_pLeft;
BinaryTreeNode * m_pRight;
//int tag;
};
int foreOrder[8] = {1, 2, 4, 7, 3, 5, 6, 8};
int inOrder[8] = {4, 7, 2, 1, 5, 3, 8, 6};
int length = 8;
BinaryTreeNode * buildTree( int * i, int first, int last)
{
if((*i) >= length) return NULL;
int j;
for(j = 0; j < length; j++)
if(inOrder[j] == foreOrder[*i])
break;
BinaryTreeNode * root = (BinaryTreeNode *)malloc(sizeof(BinaryTreeNode));
root->m_nValue = foreOrder[*i];
root->m_pLeft = NULL;
root->m_pRight = NULL;
*i += 1;
if(j > first)
root->m_pLeft = buildTree(i, first, j);
if(last > j+1)
root->m_pRight = buildTree(i, j+1, last);
return root;
}
//中序遍历
void inOrderOutput(BinaryTreeNode * root)
{
if(root == NULL) return;
inOrderOutput(root->m_pLeft);
printf("%d ", root->m_nValue);
inOrderOutput(root->m_pRight);
}
int main()
{
int i = 0;
BinaryTreeNode * root = buildTree(&i, 0, length);
inOrderOutput(root);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐