• 队列--二叉树层序遍历


    1. /*
    2. 1
    3. / \
    4. 2 3
    5. /\ /\
    6. 4 5 6 7
    7. 利用LinkedListQueue
    8. 1. 头 [1] 尾
    9. 1
    10. 2.头 [2 3] 尾
    11. 1 2
    12. 3.头 [3 4 5] 尾
    13. 1 2
    14. 4.头 [4 5 6 7] 尾
    15. 1 2 3
    16. 5.头 [] 尾
    17. 1 2 3 4 5 6 7
    18. */

    代码:

    1. class Solution {
    2. public List> levelOrder(TreeNode root) {
    3. List> result = new ArrayList<>();
    4. if(root == null) {
    5. return result;
    6. }
    7. LinkedListQueue queue = new LinkedListQueue<>();
    8. queue.offer(root);
    9. int c1 = 1; // 本层节点个数
    10. while (!queue.isEmpty()) {
    11. int c2 = 0; // 下层节点个数
    12. List level = new ArrayList<>();
    13. for (int i = 0; i < c1; i++) {
    14. TreeNode node = queue.poll();
    15. level.add(node.val);
    16. if (node.left != null) {
    17. queue.offer(node.left);
    18. c2++;
    19. }
    20. if (node.right != null) {
    21. queue.offer(node.right);
    22. c2++;
    23. }
    24. }
    25. c1 = c2;
    26. result.add(level);
    27. }
    28. return result;
    29. }
    30. // 自定义队列
    31. static class LinkedListQueue {
    32. private static class Node {
    33. E value;
    34. Node next;
    35. public Node(E value, Node next) {
    36. this.value = value;
    37. this.next = next;
    38. }
    39. }
    40. private final Node head = new Node<>(null, null);
    41. private Node tail = head;
    42. int size = 0;
    43. private int capacity = Integer.MAX_VALUE;
    44. {
    45. tail.next = head;
    46. }
    47. public LinkedListQueue() {
    48. }
    49. public LinkedListQueue(int capacity) {
    50. this.capacity = capacity;
    51. }
    52. public boolean offer(E value) {
    53. if (isFull()) {
    54. return false;
    55. }
    56. Node added = new Node<>(value, head);
    57. tail.next = added;
    58. tail = added;
    59. size++;
    60. return true;
    61. }
    62. public E poll() {
    63. if (isEmpty()) {
    64. return null;
    65. }
    66. Node first = head.next;
    67. head.next = first.next;
    68. if (first == tail) {
    69. tail = head;
    70. }
    71. size--;
    72. return first.value;
    73. }
    74. public E peek() {
    75. if (isEmpty()) {
    76. return null;
    77. }
    78. return head.next.value;
    79. }
    80. public boolean isEmpty() {
    81. return head == tail;
    82. }
    83. public boolean isFull() {
    84. return size == capacity;
    85. }
    86. }
    87. }

  • 相关阅读:
    PTA_乙级_1006
    C#的File 类使用说明
    【Mysql】mysql | 命令 | 常用命令 | 登录指明端口
    python xml 解析
    Tomcat 的部署和优化
    Java6种单例模式写法
    什么是自主系统?
    精彩回顾:CACTER邮件数据防泄露EDLP亮相2022世界互联网大会
    使用matplotlib绘制定制化饼图(图例比例标签支持中文等)
    对话式人工智能的数据采集方案
  • 原文地址:https://blog.csdn.net/m0_60333804/article/details/133441493