weixin_慕运维0044477
2019-04-27 17:13
程序如下,望大佬指点
// data_structure_explore_tree.cpp : 定义控制台应用程序的入口点。
//数组实现二叉树的储存,利用父亲结点下标*2+1是左孩子结点 父亲结点*2+2是右孩子结点
//任务:树的创建和销毁
//树中结点的搜索
//树中结点的添加与删除
//树中结点的遍历
#include "stdafx.h"
#include <iostream>
using namespace std;
class Tree {
public:
Tree(int size,int *pRoot);
~Tree();
bool AddNode(int nodeIndex, int direction, int *pNode);
int *SearchNode(int nodeIndex);//nodeIndex是结点的标识,记录结点位置
bool DeleteNode(int nodeIndex, int *pNode);
void TreeTraverse();
int *m_pTree;//记录结点的一个数组
int m_iSize;
};
Tree::Tree(int size,int *pRoot) {//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) {
//direction标识插入的结点是左还是右孩子,0表示左,1表示右
//NodeIndex表示要插入的根节点位置
if (nodeIndex < 0 || nodeIndex >= m_iSize||m_pTree[nodeIndex]==0) {
return false;
}
if (direction == 0) {
if (nodeIndex * 2 + 1 >= m_iSize||m_pTree[nodeIndex*2+1]!=0) {
return false;
}
m_pTree[nodeIndex*2+1] = *pNode;
}
if (direction == 1) {
if (nodeIndex * 2 + 2 >= m_iSize || m_pTree[nodeIndex * 2 + 2] != 0) {
return false;
}
m_pTree[nodeIndex * 2 + 2] = *pNode;
}
return true;
}
bool Tree::DeleteNode(int nodeIndex, int *pNode) {//question:删掉这个结点要不要把孩子节点删掉啊
if (nodeIndex<0 || nodeIndex>m_iSize || 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 = 3;
int node1 = 5, node2 = 8;
Tree *pTree = new Tree(10,&root);
pTree->AddNode(0, 0,&node1);
pTree->AddNode(0, 1, &node2);
int node3 = 2, node4 = 6;
pTree->AddNode(1, 0, &node3);
pTree->AddNode(1, 1, &node4);
int node5 = 9, node6 = 7;
pTree->AddNode(2, 0, &node5);
pTree->AddNode(2, 1, &node6);
pTree->TreeTraverse();
delete[]pTree;
return 0;
}
最后的delete []pTree,改成delete pTree.../(ㄒoㄒ)/~~
数据结构探险之树篇
56461 学习 · 116 问题
相似问题