- 这个实现方法比较粗糙。将二叉树所有可能的位置按次序拍好,新建树时,如果某位置没有元素,则值为0,如果有元素,则值为传入的值。
- 另外新赋值时,需要指定要在哪一个节点的左叉还是右叉插入什么值的指针?
- 其他还有删除元素,在此代码中等价为将数组该处的值置为0。等
#pragma once
#include<iostream>
#define __debug__
using namespace std;
class Array
{
public:
Array(int s);
~Array();
int get_node(int location);
bool add_head(int* node);
bool get_add(int location,int d, int* node);
bool get_delete(int location);
void traverse();
private:
int s_size;
int* pSize;
};
#include"Array.h"
Array::Array(int s)
{
s_size = s;
pSize = new int[s];
for (int i = 0; i < s; i++)
{
pSize[i] = 0;
}
}
Array::~Array()
{
delete[]pSize;
pSize = NULL;
}
bool Array::add_head(int* node)
{
pSize[0] = *node;
return true;
}
int Array::get_node(int location)
{
if (location<0 || location>s_size)
{
return -1;
}
else if(pSize[location] == 0)
{
return -1;
}
else
{
return pSize[location];
}
}
bool Array::get_add(int location, int d, int* node)
{
if (location<0 || location>= s_size)
{
return false;
}
else if (pSize[location] == 0)
{
return false;
}
else
{
if (d == 0)
{
if ((location * 2 + 1) >= s_size)
{
return false;
}
else if (pSize[location * 2 + 1] != 0)
{
return false;
}
else
{
pSize[location * 2 + 1] = *node;
return true;
}
}
else if (d == 1)
{
if ((location * 2 + 2) >= s_size)
{
return false;
}
else
{
pSize[location * 2 + 2] = *node;
return true;
}
}
return false;
}
}
bool Array::get_delete(int location)
{
if (location<0 || location>= s_size)
{
return false;
}
else if (pSize[location] == 0)
{
return false;
}
else
{
pSize[location] = 0;
return true;
}
}
void Array::traverse()
{
for (int i = 0; i < s_size; i++)
{
cout << pSize[i] << endl;
}
}
#include"Array.h"
int main()
{
Array *a=new Array(6);
int m = 2;
int m1 = 4;
int m2 = 5;
a->add_head(&m);
a->get_add(0, 1, &m1);
a->get_add(0, 0, &m2);
int m5 = a->get_node(4);
cout << m5 << endl;
cout << endl;
a->traverse();
delete a;
return 0;
}
Higher you climb, more view you will see.