您的位置:首页 > 其它

二叉树数组存储结构实现

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

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐