二叉树数组存储结构实现

不是满二叉树的话非常浪费空间,一般就在堆排序中用了,写这个一般操作纯粹是因为坑爹的软设作业= =

#ifndef arrayBinaryTree_H_
#define arrayBinaryTree_H_
#define maxsize 1000
#include <iostream>
#include <stack>
#include <cstdlib>
#include <cstring>
using namespace std;

class arrayBinaryTree
{
private:
    int num;
    char node[maxsize];
public:
    arrayBinaryTree();
    //~arrayBinaryTree();
    void creat();
    void preOrder();
};

arrayBinaryTree::arrayBinaryTree()
{
    cout<<"please input the num of the node(include the empty node)"<<endl;
    cin>>num;
}

void arrayBinaryTree::creat()
{
    memset(node,'#',sizeof(node));
    int i;
    for(i=0; i<num; i++)
    {
        cin>>node[i];
    }
}

void arrayBinaryTree::preOrder()
{
    int temp;
    stack<int>S;
    S.push(0);
    while(!S.empty())
    {
        temp=S.top();
        S.pop();
        cout<<node[temp]<<" ";
        int lchild=temp*2+1;
        int rchild=temp*2+2;
        if(node[rchild]!='#')
            S.push(rchild);
        if(node[lchild]!='#')
            S.push(lchild);
    }
}
#endif

测试:

#include <iostream>
#include "arrayBinaryTree.h"
using namespace std;

int main()
{
    //input
    //31
    //A#B##CD####EF#G################
    arrayBinaryTree test;
    test.creat();
    test.preOrder();
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值