从数组创建完全二叉树

由给定的数组创建一颗二叉树。

#include 
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<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:"<


你可能感兴趣的:(数据结构)