您的位置:首页 > 编程语言 > C语言/C++

重建二叉树(C++递归实现)

2016-03-05 21:44 531 查看
#include<stack>

#include<queue>

#include<iostream>

using namespace std;

typedef struct Node{

    Node* left;

    Node* right;

    char data;

    Node(char c)

    {

        data=c;

        left=NULL;//很重要

        right=NULL;

    }

    ~Node()

    {

        delete left;//如果left为null,也没问题,delete兼容null

        delete right;

    }

}*BiTree;

#define TREELEN 6

Node* rebuild(char *preOrder,char *inOrder,int n)

{

    if(n==0) return NULL;

    //获得前序遍历的第一个节点

    char c=preOrder[0];

    Node *node=new Node(c); //This is the root node of this tree/sub tree.

    int i;

    for( i=0;i<n && inOrder[i]!=c;i++)

            ;

    int  lenL=i; //// the node number of the left child tree.

    int     lenR=n-i-1;//// the node number of the rigth child tree.

                  //为什么减1,因为中间的元素占了一个

    if(lenL>0)

        node->left=rebuild(&preOrder[1],&inOrder[0],lenL);

    if(lenR>0)

        node->right=rebuild(&preOrder[lenL+1],&inOrder[lenL+1],lenR);

    return node;

}

void levelOrder(BiTree T)

{

    queue<BiTree> q;

    q.push(T);

    while(!q.empty())

    {

        BiTree h=q.front();q.pop();

        cout<<h->data<<ends;

        if(h->left) q.push(h->left);

        if(h->right) q.push(h->right);

    }

}

void PostOrder(BiTree T)

{

    if(T == NULL)

        return;

    //左子树

    if(T->left != NULL)

        PostOrder(T->left);

    //右子树

    if(T->right != NULL)

        PostOrder(T->right);

    //根

    cout<<T->data<<' ';

}

int main()

{

    char szPreOrder[TREELEN]={'a','b','d','c','e','f'};

    char szInOrder[TREELEN]={ 'd', 'b','a','e','c','f'};

    Node *result=rebuild(szPreOrder,szInOrder,6);

    cout<<"PostOrder:"<<endl;

    PostOrder(result);

    cout<<endl;

    cout<<"levelOrder:"<<endl;

    levelOrder(result);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: