PTA列出叶结点 (25分)

古城微笑少年丶 2023-07-23 03:48 227阅读 0赞

题目
【程序思路】
按从上到下、从左到右的顺序输出,则是层序遍历的顺序,这里需要用到队列。首先需要根据输入找出根节点,将输入利用静态链表的方式保存,没有被指向的编号就是根节点。然后再根据层序遍历遍历树,若该节点为叶子节点则将其编号保存,最后输出。
【程序实现】

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. struct tree{
  4. int left,right;
  5. }a[15];
  6. int main(){
  7. int n,check[15] = {
  8. 0},head,p[10],j = 0;
  9. queue<int> q;
  10. cin>>n;
  11. for (int i = 0; i < n; i++) {
  12. char l,r;
  13. cin>>l>>r;
  14. a[i].left = l != '-' ? l-'0' : 12;//12表示空
  15. a[i].right = r != '-' ? r-'0' : 12;
  16. check[a[i].left] = 1;
  17. check[a[i].right] = 1;
  18. }
  19. for (head = 0; head < n;head++)
  20. if (!check[head]) break;
  21. q.push(head);
  22. while(!q.empty()) {
  23. int i = q.front();
  24. q.pop();
  25. if(i == 12) continue;
  26. if(a[i].left == 12 && a[i].right == 12)
  27. p[j++] = i;
  28. q.push(a[i].left);
  29. q.push(a[i].right);
  30. }
  31. cout<<p[0];
  32. for (int i = 1; i < j; i++)
  33. cout<<' '<<p[i];
  34. return 0;
  35. }

发表评论

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

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

相关阅读

    相关 单链表删除--PTA

    本题要求实现两个函数,分别将读入的数据存储为单链表、将链表中所有存储了某给定值的结点删除。链表结点定义如下: struct ListNode {