• 2014软专算法题T1


    如果要对二叉树进行自下而上,自右向左的层次遍历,请给出遍历算法。

    解题思路:ggt

    1.采用层次遍历,初始化一个空队列和空栈

    2.每次出队时将该元素入栈,直至层次遍历结束

    3.不断将栈顶元素出栈,同时对其访问,直至栈空

     ps:偷懒将层次遍历的序列存入数组中,在将数组中的data值逆序输出,即可得到反向层次遍历的序列

    1. #include
    2. #include
    3. #include
    4. using namespace std;
    5. //string qx="12400500300";//完全二叉树测试数据
    6. //string zx="04020501030";
    7. string qx="123" ;//非完全二叉树测试数据
    8. string zx="321";
    9. const int MaxSize=100;
    10. typedef struct Tree//二叉树结构定义
    11. {
    12. int data;
    13. Tree *left;
    14. Tree *right;
    15. } *BiTree;
    16. BiTree build(string qx,string zx)//建树
    17. {
    18. if(qx.size()==0)return NULL;
    19. Tree *root=(Tree *)malloc(sizeof(Tree));
    20. root->data=qx[0]-'0';
    21. int pos=zx.find(qx[0]);
    22. root->left=build(qx.substr(1,pos),zx.substr(0,pos));
    23. root->right=build(qx.substr(pos+1),zx.substr(pos+1));
    24. return root;
    25. }
    26. typedef struct LinkNode//队列结点
    27. {
    28. BiTree data;
    29. LinkNode *next;
    30. }LinkNode,*Link;
    31. typedef struct Queue//链队列
    32. {
    33. LinkNode *front;
    34. LinkNode *rear;
    35. }*queue;
    36. void InitQueue(Queue &Q)
    37. {
    38. Q.front=Q.rear=(LinkNode*)malloc(sizeof(LinkNode));
    39. Q.front->next=NULL;
    40. }
    41. bool isEmpty(Queue Q)
    42. {
    43. if(Q.front==Q.rear) return true;
    44. else return false;
    45. }
    46. void EnQueue(Queue &Q,BiTree x)
    47. {
    48. LinkNode *p=(LinkNode*)malloc(sizeof(LinkNode));
    49. p->data=x;
    50. p->next=Q.rear->next;
    51. Q.rear->next=p;
    52. Q.rear=p;
    53. }
    54. bool DeQueue(Queue &Q,BiTree &x)
    55. {
    56. if(Q.front==Q.rear) return false;
    57. LinkNode *p=Q.front->next;
    58. x=p->data;
    59. Q.front->next=p->next;
    60. if(Q.rear==p) Q.rear=Q.front;
    61. return true;
    62. }
    63. void LevelOrder(BiTree T)//层次遍历
    64. {
    65. int a[10];
    66. int i=0;
    67. BiTree x;
    68. Queue Q;
    69. InitQueue(Q);
    70. BiTree p=T;
    71. EnQueue(Q,p);
    72. while(!isEmpty(Q))
    73. {
    74. DeQueue(Q,x);
    75. a[i++]=x->data;//将层次遍历得到的序列存入数组中
    76. if(x->left!=NULL)
    77. EnQueue(Q,x->left);
    78. if(x->right!=NULL)
    79. EnQueue(Q,x->right);
    80. }
    81. for(int j=i-1;j>=0;j--)//将数组中的data值逆序输出
    82. {
    83. printf("%d ",a[j]);
    84. }
    85. }
    86. int main()
    87. {
    88. BiTree T=build(qx,zx);
    89. LevelOrder(T);
    90. }

  • 相关阅读:
    Less语法简介
    信息论随笔(三)交互信息量
    Mojo 摸脚语言,似乎已经可以安装
    Java中interrupt的理解(个人)
    【从零开始的Java开发】2-8-2 CSS入门:CSS选择器、样式
    Boost ASIO:io_service 与 strand 的使用
    2023-10-28 LeetCode每日一题(从数量最多的堆取走礼物)
    动捕设备推动舞蹈表演动作捕捉动画制作突破边界
    ubuntu 安装postgresql,增加VECTOR向量数据库插件 踏坑详细流程
    Ros cartographer pure localization 自定位+重定位+导航
  • 原文地址:https://blog.csdn.net/UncleJokerly/article/details/127970839