zoukankan      html  css  js  c++  java
  • 7-9 还原二叉树(25 分)

    给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。

    输入格式:

    输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。

    输出格式:

    输出为一个整数,即该二叉树的高度。

    输入样例:

    9
    ABDFGHIEC
    FDHGIBEAC
    

    输出样例:

    5
    

    代码:

    #include <stdio.h>
    #include <stdlib.h>
    
    char x[50],z[50];
    typedef struct TreeNode *Tree;
    struct TreeNode
    {
        char data;
        Tree right,left;
    };
    Tree CreatNode()
    {
        Tree p = (Tree)malloc(sizeof(struct TreeNode));
        p -> left = p -> right = NULL;
        return p;
    }
    Tree RestoreTree(int x1,int x2,int z1,int z2)
    {
        Tree head = CreatNode();
        head -> data = x[x1];
        for(int i = z1;i <= z2;i ++)
        {
            if(z[i] == x[x1])
            {
                if(i != z1)head -> left = RestoreTree(x1 + 1,x1 + i - z1,z1,i - 1);
                if(i != z2)head -> right = RestoreTree(x1 + i - z1 + 1,x2,i + 1,z2);
                break;
            }
        }
        return head;
    }
    int max(int a,int b)
    {
        if(a>b)return a;
        return b;
    }
    int Theight(Tree tree)
    {
        if(tree == NULL)return 0;
        return max(Theight(tree -> left),Theight(tree -> right))+1;
    }
    int main()
    {
        int n;
        scanf("%d",&n);
        scanf("%s%s",x,z);
        Tree head = RestoreTree(0,n-1,0,n-1);
        printf("%d",Theight(head));
    }
  • 相关阅读:
    POJ 2773 Happy 2006------欧几里得 or 欧拉函数。
    Candies
    subway(dijkstra以最短时间代替最短路)
    昂贵的聘礼
    LightOJ 1074
    SPFA以及各种优化
    Making Huge Palindromes (Manacher)
    Making Huge Palindromes (KMP处理回文串)
    AC自动机基础
    扩展KMP
  • 原文地址:https://www.cnblogs.com/8023spz/p/7701244.html
Copyright © 2011-2022 走看看