树的顺序表存储:
二叉树的定义:
class TREE
{
int data[100];
int n;
public:
TREE(){
}
void settree()
{
cin >> n;
data[0]=0;
for(int i=1;i<=n;i++)
{
cin >> data[i];
}
}
};
前序遍历:
void preorderprint(int num)
{
if(num<0||num>n||data[num]==0)return;
cout << data[num] << " ";
preorderprint(num*2);
preorderprint(num*2+1);
}
中序遍历:
void inorderprint(int num)
{
if(num<0||num>n||data[num]==0)return;
inorderprint(num*2);
cout << data[num] << " ";
inorderprint(num*2+1);
}
后序遍历:
void postorderprint(int num)
{
if(num<0||num>n||data[num]==0)return;
postorderprint(num*2);
postorderprint(num*2+1);
cout << data[num] << " ";
}
树的链式存储:
二叉树的定义:
//队列定义
class QUEUE{
NODE* data;
int n;
int first,last;
public:
QUEUE(int n=0){
data=new NODE[n];
first=0;
last=0;
this->n=0;
}
void push(NODE* value){
data[last].data=value->data;
data[last].left=value->left;
data[last].right=value->right;
n++;
last++;
}
NODE pop(){
n--;
return data[first++];
}
bool ifempty()
{
return n==0?true:false;
}
friend class TREE;
};
//树节点
class NODE {
int data;
NODE* left;
NODE* right;
public:
NODE(int data=0) {
this->data = data;
left = nullptr;
right = nullptr;
}
};
//树的链式存储
class TREE {
NODE* root;
int n;
public:
TREE() {
root = nullptr;
n = 0;
}
NODE* getroot() {
return root; //得到根节点地址
}
NODE* settree(int* pre, int* in, int n) {
if (n == 0)return nullptr;
int k = 0;
while (pre[0] != in[k])k++;
NODE* t = new NODE(pre[0]);
t->left = settree(pre + 1, in, k);
t->right = settree(pre + k + 1, in + k + 1, n - k - 1);
return t;
}
void set(int* pre, int* in, int n) {
root = settree(pre, in, n);
this->n = n;
}
};
前序遍历:
void postorderprint(NODE* p) {
if (p != nullptr) {
cout << p->data << " ";
postorderprint(p->left);
postorderprint(p->right);
}
}
中序遍历:
void postorderprint(NODE* p) {
if (p != nullptr) {
postorderprint(p->left);
cout << p->data << " ";
postorderprint(p->right);
}
}
后序遍历:
void postorderprint(NODE* p) {
if (p != nullptr) {
postorderprint(p->left);
postorderprint(p->right);
cout << p->data << " ";
}
}
层序遍历(栈实现):
void sequenceprint(int n) { //层序遍历
QUEUE que(n);
que.push(root);
while(1){
NODE p=que.pop();
cout << p.data << " ";
if(p.left)que.push(p.left);
if(p.right)que.push(p.right);
if(que.ifempty())break;
}
}