关于数据结构中的树,james老师的授课内容
我打印出来的是 3 5 8 2 6 9 0 0 0 0 120,后面有个120是怎么回事啊
#include<iostream> #include<stdlib.h> using namespace std; 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;//记录数组的大小 }; Tree::Tree(int size,int *pRoot) { m_iSize=size; m_pTree = new int[size];//申请内存 for(int i;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) { 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) { 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]<<" "; } } 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); int node=0; pTree->DeleteNode(6,&node); cout<<" node ="<<node<<endl; pTree->TreeTraverse(); int *p=pTree->SearchNode(2); cout<<endl; cout<<" node ="<<*p<<endl; delete pTree; system("pause"); return 0; }