照着代码打的,不出现结果?什么都没有,求解!!!
为什么我的不出现结果?什么都没有,谁可以帮帮忙?
demo.cpp:
#include <iostream>
#include <stdlib.h>
#include "Tree.h"
using namespace std;
int main(void)
{
int root = 3;
Tree *pTree = new Tree(10,&root);
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);
pTree->TreeTraverse();
int *p = pTree->SearchNode(2);
cout<< endl <<"node="<<*p<<endl;
delete pTree;
system("pause");
return 0;
}
Three.cpp:
#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 <size;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 == 0)//0代表插入左孩子
{
if(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)//1代表插入右孩子
{
if(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] << " ";
}
}
Three.h:
#ifndef TREE_H
#define TREE_H
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();//遍历结点
private:
int *m_pTree;
int m_iSize;
};
#endif