注意点:1、增添时,增添的是父节点的下标,然后选择左右。
2、查找和删除时,查找和删除的即为那个结点。
#include <iostream>
#include <stdio.h>
using namespace std;
class Tree{
public:
Tree(int size,int *pRoot); //构造函数,有大小这个参数
~Tree(); //析构函数
int *SearchNoid(int nodeIndex); //根据索引寻找结点,然后定义一个指针接受这个值*p= *SearchNoid(0);
bool AddNode(int nodeIndex,int direction,int *pNode); //(结点,左右,插入的值)
bool DeleteNode(int nodeIndex,int *pNode); //删除结点,然后把值返回
void TreeTraverse(); //遍历结点
private:
int *m_pTree;
int m_iSize;
};
Tree::Tree(int size,int *pRoot){
m_iSize=size;
m_pTree=new int[size]; //从堆中分配size给m_pTree ,实例化了一个类
for(int i=0;i<size;i++){
m_pTree[i]=0;
}
m_pTree[0]=*pRoot;
}
Tree::~Tree(){
delete []m_pTree;
m_pTree=NULL;
}
int *Tree::SearchNoid(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==0){
if(nodeIndex*2+1<0||nodeIndex*2+1>=m_iSize){
return false;
}
if(m_pTree[nodeIndex*2+1]!=0){
return false;
}
m_pTree[nodeIndex*2+1]=*pNode;
}
if(direction==1){
if(nodeIndex*2+2<0||nodeIndex*2+2>=m_iSize){
return false;
}
if(m_pTree[nodeIndex*2+2]!=0){
return false;
}
m_pTree[nodeIndex*2+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] << " ";
}
}
int main(){
int root=10;
Tree *pTree=new Tree(10,&root); //此处为new一个类树。
int node1=5;
int node2=8;
pTree->AddNode(0,0,&node1); //插入一个数的时候,应该给这个数取地址
pTree->AddNode(0,1,&node2);
int node3=2;
int node4=6;
pTree->AddNode(1,0,&node3);
pTree->AddNode(1,1,&node4);
int node5=9;
int node6=7;
pTree->AddNode(2,0,&node5);
pTree->AddNode(2,1,&node6);
int node7=456321;
pTree->AddNode(3,0,&node7);
int node=0;
pTree->DeleteNode(6,&node); //删除也为取地址
cout << "node4=" << node << endl;
pTree->TreeTraverse();
int *p=pTree->SearchNoid(0);
cout << "node=" << *p << endl;
delete pTree;
return 0;
}