通過前序遍歷和中序遍歷確定二叉樹,並輸出后序遍歷序列


我們知道,中序遍歷和前序或者后序能夠唯一確定一顆二叉樹,因此,給定前序遍歷以及中序遍歷序列能夠確定建立這顆二叉樹,然后后序遍歷便能夠得到相應的序列

代碼如下(內含二叉樹的建立,求二叉樹的高度)

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
typedef struct Node{
    Node *lchild;
    Node *rchild;
    char c;
}Node,*Tree;//靜態內存分配數組
//int loc;
char str1[30];
char str2[30];
Node *createNode(){
//    Tree[loc].lchild = Tree[loc].rchild=NULL;
//    return &Tree[loc++];
    Tree node = (Tree)malloc(sizeof(Node));
    if (node) {
        node->lchild=node->rchild=nullptr;
        return node;
    }else{
        printf("無法分配節點");
        exit(0);
    }
    
}
//后序遍歷算法
void postOrder(Node *T){
    if (T->lchild!=NULL) {
        postOrder(T->lchild);
    }
    if (T->rchild!=NULL) {
        postOrder(T->rchild);
    }
    printf("%c",T->c);
   
}
//先序遍歷
void preOrder(Tree T){
    printf("%c",T->c);
    if (T->lchild!=NULL) {
        preOrder(T->lchild);
    }
    if (T->rchild!=NULL) {
        preOrder(T->rchild);
    }
}
//中序遍歷
void midOrder(Tree T){
    if (T->lchild!=NULL) {
        midOrder(T->lchild);
    }
    printf("%c",T->c);
    if (T->rchild!=NULL) {
        midOrder(T->rchild);
    }

}

Node * build(int s1,int e1,int s2,int e2){
    //根據前序遍歷序列str1和中序遍歷序列str2構建樹,並返回樹的根節點,
    Node * ret = createNode();//構建根節點,
    ret->c = str1[s1];
    int rootIdx;
    for (int i = s2; i<=e2;i++ ) {
        if (str2[i]==str1[s1]) {
            rootIdx = i;//在中序遍歷序列中找到根節點的下標;
            break;
        }
    }
    if(rootIdx!=s2){//說明左子樹不為空
        ret->lchild = build(s1+1, s1+(rootIdx-s2), s2, rootIdx-1);
    }
    if (rootIdx!=e2) {//說明右子樹不為空
        ret->rchild=build(s1+(rootIdx-s2)+1, e1, rootIdx+1, e2);
        
    }
    return ret;
}
//建立一顆二叉樹,前序
Node *buildTree(){
    //輸入字符建立二叉樹,遇到#便設置這個節點為空
    Node *root =(Tree)malloc(sizeof(Node));
    char a;
    scanf("%c",&a);
    if (a=='#') {
        root = nullptr;
    }else{
        root->c = a;
        root->lchild = buildTree();
        root->rchild = buildTree();
    }
    return root;
}
//求樹的高度
int high_Tree(Tree T){
    if (T==nullptr) {
        return 0;
    }else{
        int lh = high_Tree(T->lchild);
        int rh = high_Tree(T->rchild);
        return lh>rh?lh+1:rh+1;
    }
        
}
int main() {
    while(scanf("%s",str1)!=EOF){
        scanf("%s",str2);
        int L1 = strlen(str1);
        int L2 = strlen(str2);
        Node * T = build(0, L1-1, 0, L2-1);
        postOrder(T);
        printf("%d\n",high_Tree(T));
        printf("\n");
    }
    

    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM