PTA练习题:还原二叉树

小咪咪 2023-02-11 15:26 22阅读 0赞

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

输入格式:

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

输出格式:

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

输入样例:

9
ABDFGHIEC
FDHGIBEAC
输出样例:

5

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. typedef char ElementType;
  4. typedef struct TNode *Position;
  5. typedef Position BinTree;
  6. struct TNode{
  7. ElementType Data;
  8. BinTree Left;
  9. BinTree Right;
  10. };
  11. BinTree SetBinTree(char per[],char od[]);
  12. int GetIndex(char s[],char c);
  13. int GetHeight( BinTree BT );
  14. int i = 0;
  15. int main()
  16. {
  17. int n;
  18. scanf("%d",&n);
  19. getchar();
  20. char per[51];
  21. char od[51];
  22. gets(per);
  23. gets(od);
  24. BinTree BT = SetBinTree(per,od);
  25. printf("%d\n",GetHeight(BT));
  26. return 0;
  27. }
  28. BinTree SetBinTree(char per[],char od[])
  29. {
  30. int x = GetIndex(od,per[i]);
  31. if( x == -1)
  32. {
  33. i--;
  34. return NULL;
  35. }
  36. BinTree T = (BinTree)malloc(sizeof(struct TNode));
  37. T->Data = per[i];
  38. char od1[51];
  39. char od2[51];
  40. int count1 = 0;
  41. int count2 = 0;
  42. for(int j=0;j<x;j++)
  43. {
  44. od1[count1++] = od[j];
  45. }
  46. for(int j=x+1;od[j]!='\0';j++)
  47. {
  48. od2[count2++] = od[j];
  49. }
  50. i++;
  51. T->Left = SetBinTree(per,od1);
  52. i++;
  53. T->Right = SetBinTree(per,od2);
  54. return T;
  55. }
  56. int GetIndex(char s[],char c)
  57. {
  58. for(int i=0;s[i]!='\0';i++)
  59. {
  60. if(s[i] == c)
  61. {
  62. return i;
  63. }
  64. }
  65. return -1;
  66. }
  67. int GetHeight( BinTree BT )
  68. {
  69. if(BT == NULL)
  70. {
  71. return 0;
  72. }
  73. return GetHeight(BT->Left)+1>GetHeight(BT->Right)+1? GetHeight(BT->Left)+1:GetHeight(BT->Right)+1;
  74. }

发表评论

表情:
评论列表 (有 0 条评论,22人围观)

还没有评论,来说两句吧...

相关阅读