Use recursive thinking to do binary tree (traversal operation)

#include<iostream>
#include<stdlib.h>
#include<string.h>




using namespace std;


const int capacity=100;


typedef struct Node
{
    char data;
    struct Node *l;
    struct Node *r;
} TreeNode;




class STree
{
private:
    int index;
    int front,rear,num;
    TreeNode *Q[100];
public:
    STree()
    {
        index = -1;
        front=rear=-1;
        num=0;
    }
    ~STree()
    {
    }
    TreeNode * buildtrees(char *s)
    {
        index ++;
        TreeNode * node = NULL;
        if(index < strlen(s))
        {
            char a = s[index];
            if(a == '#')
            {
                return NULL;
            }
            else
            {
                node = (TreeNode *)malloc(sizeof(TreeNode));
                node->data = a;
                node->l = buildtrees(s);
                node->r = buildtrees(s);
            }
        }
        num=index;
        return node;
    }
    void postOrder(TreeNode * root)
    {
        if(root == NULL)
        {
            return;
        }
        cout << root->data << " ";
        postOrder(root->l);
        postOrder(root->r);
    }
    void preOrder(TreeNode * root)
    {
        if(root == NULL)
        {
            return;
        }
        preOrder(root->l);
        preOrder(root->r);
        cout << root->data << " ";
    }
    void inOrder(TreeNode * root)
    {
        if(root == NULL)
        {
            return;
        }
        inOrder(root->l);
        cout << root->data << " ";
        inOrder(root->r);
    }
//层序
    void leverOrder(TreeNode * root)
    {
        front=rear=-1;
        TreeNode *q;
        q=(TreeNode *)malloc(sizeof(TreeNode*));
        if(root==NULL)
        {
            return;
        }
        Q[++rear]=root;
        while(front!=rear)
        {
            q=Q[++front];
            cout<<q->data<<" ";
            if(q->l!=NULL)
            {
                Q[++rear]=q->l;
            }
            if(q->r!=NULL)
            {
                Q[++rear]=q->r;
            }
        }


    }
};




int main()
{
    char * s = "ABD#G###CE##F##";
    STree p;
    TreeNode * root = p.buildtrees(s);
    cout << "前序" << endl;
    p.postOrder(root);
    cout << endl;
    cout << "后序" << endl;
    p.preOrder(root);
    cout << endl;
    cout << "中序" << endl;
    p.inOrder(root);
    cout<<endl;
    cout<<"层序"<<endl;
    p.leverOrder(root);
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325919731&siteId=291194637