这是个什么问题
Tree.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
Tree.cpp
#include<iostream> #include"Tree.h" using namespace std; Tree::Tree(int size, int *pRoot) { m_pTree = new int[size]; m_iSize = 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) //节点数值为0代表不存在该节点 return NULL; return &m_pTree[nodeIndex]; } /* 左子节点下标号是父节点下标号*2+1 右子节点是父节点下标号*2+2 */ 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; } void Tree::TreeTraverse() { for (int i = 0; i < m_iSize; i++) { cout << m_pTree[i] << " "; } }
main.cpp
#include<iostream> #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); int node = 0; pTree->DeleteNode(6, &node); cout <<"node="<< node<<endl; pTree->TreeTraverse(); cout << endl; int *p=pTree->SearchNode(2); cout << *p; delete[]pTree; pTree = NULL; system("pause"); return 0; }