剑指offer之分行从上到下打印二叉树

举报
chenyu 发表于 2021/07/27 00:23:02 2021/07/27
【摘要】 1 题目 分行从上到下打印二叉树                   2               3    5         &...

1 题目

分行从上到下打印二叉树


  
  1.                   2
  2.                3    5           
  3.              1  4  2  3 

我们打印如下


  
  1. 2
  2. 3     5
  3. 1     4     2     3

 

 

 

2 分析

之前这篇博客写了通过队列按层打印剑指offer之按层打印树节点

 现在无非就是还要按照条件打印,第一次打印1个,然后第二次打印2个,第三次打印4个,我们可以这样,搞2个变量,第一个变量表示这行还没有打印的个数,另外一个变量是下列需要打印的个数,如果这一行还没有打印的个数是0了,我们就把下列需要打印值个数赋值给它,然后下一列变量的个数变量赋值为0.

 

 

 

3 代码实现


  
  1. #include <iostream>
  2. #include <queue>
  3. using namespace std;
  4. typedef struct Node
  5. {
  6. int value;
  7. struct Node* left;
  8. struct Node* right;
  9. } Node;
  10. void layer_print(Node *head)
  11. {
  12. if (head == NULL)
  13. {
  14. std::cout << "head is NULL" << std::endl;
  15. return;
  16. }
  17. std::queue<Node *> queue;
  18. queue.push(head);
  19. //下一列需要打印节点的个数
  20. int next_print_count = 0;
  21. //当前这一列还需要打印节点的个数
  22. int has_print_count = 1;
  23. while(queue.size())
  24. {
  25. Node *node = queue.front();
  26. std::cout << node->value << "\t";
  27. if (node->left)
  28. {
  29. queue.push(node->left);
  30. next_print_count++;
  31. }
  32. if (node->right)
  33. {
  34. queue.push(node->right);
  35. next_print_count++;
  36. }
  37. queue.pop();
  38. has_print_count--;
  39. if (has_print_count == 0)
  40. {
  41. has_print_count = next_print_count;
  42. next_print_count = 0;
  43. std::cout << std::endl;
  44. }
  45. }
  46. }
  47. int main()
  48. {
  49. /* 2
  50. * 3 5
  51. * 1 4 2 3
  52. *
  53. */
  54. Node head1, node1, node2, node3, node4, node5, node6;
  55. Node head2, node7, node8;
  56. head1.value = 2;
  57. node1.value = 3;
  58. node2.value = 5;
  59. node3.value = 1;
  60. node4.value = 4;
  61. node5.value = 2;
  62. node6.value = 3;
  63. head1.left = &node1;
  64. head1.right = &node2;
  65. node1.left = &node3;
  66. node1.right = &node4;
  67. node2.left = &node5;
  68. node2.right = &node6;
  69. node3.left = NULL;
  70. node3.right = NULL;
  71. node4.left = NULL;
  72. node4.right = NULL;
  73. node5.left = NULL;
  74. node5.right = NULL;
  75. node6.left = NULL;
  76. node6.right = NULL;
  77. layer_print(&head1);
  78. return 0;
  79. }

 

 

 

4 运行结果


  
  1. 2
  2. 3 5
  3. 1 4 2 3

 

 

5 总结

通过第一行的打印的个数,我们找到第二列打印的个数,通过第二行打印的个数,我们需要打印第三行需要打印的个数,我们可以用2个变量来搞定。

文章来源: chenyu.blog.csdn.net,作者:chen.yu,版权归原作者所有,如需转载,请联系作者。

原文链接:chenyu.blog.csdn.net/article/details/90322506

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。