实现算法:二叉树从上到下,从左往右进行编号,然后放入数组中。
ps:对二叉树进行操作时,对下标和该节点是否有值要进行判断
- main文件
#include <iostream>
#include "Tree.h"
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
int root = 3;
Tree *pTree = new Tree(10,&root);
int node1 = 5;
int node2 = 8;
pTree->AddNode(0,1,&node1);
pTree->AddNode(0,0,&node2);
int node3 = 2;
int node4 = 6;
pTree->AddNode(1,1,&node3);
pTree->AddNode(1,0,&node4);
int node5 = 9;
int node6 = 7;
pTree->AddNode(2,1,&node5);
pTree->AddNode(2,0,&node6);
pTree->TreeTraverse();
int *p = pTree->SearchNode(4);//Search返回的是一个指针,用指针接收
cout << endl << "node = " << *p <<endl;
int temp = 0;
pTree->DeleteNode(3,&temp);
cout << "deleted number:" << temp << endl;
pTree->TreeTraverse();
delete pTree;
pTree = NULL;
return 0;
}
- Tree文件
class Tree
{
public:
Tree( int size,int *pRoot );//创建树
~Tree();
int *SearchNode( int nodeIndex );// 根据索引寻找节点
bool AddNode( int nodeIndex,int direction,int *pNode );//添加节点
bool DeleteNode( int nodeIndex,int *pNode );//删除节点
void TreeTraverse();//遍历节点
protected:
int *m_pTree;
int m_iSize;
};
#include <iostream>
#include "Tree.h"
using namespace std;
Tree :: Tree(int size,int *pRoot){
m_iSize = size;
m_pTree = new int[size];
for( int i = 0;i < m_iSize;i++ ){
m_pTree[i] = 0;
}
m_pTree[0] = *pRoot;
}
Tree:: ~Tree(){
delete []m_pTree;//删除的是一个动态数组 ,加【】
m_pTree = NULL;
}
int* Tree:: SearchNode( int nodeIndex ){
if(nodeIndex < 0 || nodeIndex >= m_iSize){
return NULL;
}
if( m_pTree[nodeIndex] == 0)
return NULL;
return &m_pTree[nodeIndex];
}
bool Tree:: AddNode( int nodeIndex,int direction,int *pNode ){
if(nodeIndex < 0 || nodeIndex >= m_iSize){
return false;
}
if( m_pTree[nodeIndex] == 0)
return false;
if( direction == 1 ){
if( 2*nodeIndex +1 >= m_iSize )
return false;
if( m_pTree[nodeIndex*2 +1] != 0 )
return false;
m_pTree[2*nodeIndex + 1] = *pNode;
}
if(direction == 0 ){
if( 2*nodeIndex +2 >= m_iSize )
return false;
if( m_pTree[nodeIndex*2 + 2] != 0 )
return false;
m_pTree[2*nodeIndex + 2] = *pNode;
}
return true;
}
bool Tree:: DeleteNode( int nodeIndex,int *pNode ){
if( nodeIndex < 0 || nodeIndex >= m_iSize )
return false;
if( m_pTree[nodeIndex] = 0)
return false;
*pNode = m_pTree[nodeIndex];
m_pTree[nodeIndex] = 0;
return true;
}
void Tree:: TreeTraverse(){
for(int i = 0 ;i < m_iSize;i++ ){
cout << m_pTree[i] << " ";
}
}
演示结果: