您的位置:首页 > 其它

从数组创建完全二叉树

2013-10-17 11:49 330 查看
由给定的数组创建一颗二叉树。

#include <iostream>
using namespace std;

struct Node{
int   m_nData;
Node *m_pLeft;
Node *m_pRight;
};

Node* buildCore(int *piValue, int iStart, int iLength)
{
if (iStart>=iLength){
return NULL;
}

Node *pRoot = new Node;
pRoot->m_nData  = piValue[iStart];
pRoot->m_pLeft  = buildCore(piValue, iStart*2+1, iLength);
pRoot->m_pRight = buildCore(piValue, iStart*2+2, iLength);

return pRoot;
}

Node* buildCompleteBinaryTree(int *piValue, int iLength)
{
if (piValue==NULL || iLength<=0){
return NULL;
}

return buildCore(piValue, 0, iLength);
}

void preOrder_Recursive(Node *pRoot)
{
if (pRoot){
cout<<pRoot->m_nData<<" ";
preOrder_Recursive(pRoot->m_pLeft);
preOrder_Recursive(pRoot->m_pRight);
}
}

int main()
{
int data[9] = {1,2,3,4,5,6,7,8,9};
Node *pRoot = buildCompleteBinaryTree(data, 9);

cout<<"Pre-Order traverse:"<<endl;
preOrder_Recursive(pRoot);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: