郑州做网站推广价格站长工具查询网站
一 实现二叉树的按层遍历
1.1 描述
1)其实就是宽度优先遍历,用队列
2)可以通过设置flag变量的方式,来发现某一层的结束(看题目)看下边的第四题解答
1.2 代码
public class Code01_LevelTraversalBT {public static class Node {public int value;public Node left;public Node right;public Node(int v) {value = v;}}public static void level(Node head) {if (head == null) {return;}Queue<Node> queue = new LinkedList<>();queue.add(head);while (!queue.isEmpty()) {Node cur = queue.poll();System.out.println(cur.value);if (cur.left != null) {queue.add(cur.left);}if (cur.right != null) {queue.add(cur.right);}}}