二叉树代码实现

二叉树

基本代码

建树、前序、中序、后序遍历

#include
using namespace std;

//树的结构体
struct tree
{
    char data;
    tree* left;
    tree* right;
};

//建立树
tree* setTree(string& s,int& index)
{
    if(index>=s.size()||s[index]=='#') 
    {
        index++;
        return NULL;
    }
    else 
    {   
        tree* t = new tree;
        t->data = s[index];
        index++;
        t->left=setTree(s,index);
        t->right=setTree(s,index);
        return t;
    }
}

//前序遍历
void prior(tree* t)
{
    if(t==NULL) return ;
    cout<<t->data;
    prior(t->left);
    prior(t->right);
}

//中序遍历
void middle(tree* t)
{
    if(t==NULL) return ;
    middle(t->left);
    cout<<t->data;
    middle(t->right);
}

//后序遍历
void last(tree* t)
{
    if(t==NULL) return ;
    last(t->left);
    last(t->right);
    cout<<t->data;
}

int main()
{
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        string s;
        cin>>s;
        int index = 0;
        tree* p=setTree(s,index);
        prior(p);
        cout<<endl;
        middle(p);
        cout<<endl;
        last(p);
        cout<<endl;
    }
    return 0;
}
#include
using namespace std;

//有父节点的树结构体
struct tree
{
    char data;
    tree* dad;
    tree* left;
    tree* right;
};

//有父节点的建树
tree* setTree(string& s,int& index,tree* dad)
{
    if(index>=s.size()||s[index]=='0') 
    {
        index++;
        return NULL;
    }
    else 
    {   
        tree* t = new tree;
        t->data = s[index];
        t->dad = dad;
        index++;
        t->left=setTree(s,index,t);
        t->right=setTree(s,index,t);
        return t;
    }
}

你可能感兴趣的:(算法,数据结构)