二叉树系列--层序遍历(java实现)

来源:互联网 发布:音视频矩阵怎么控制 编辑:程序博客网 时间:2024/06/05 04:38

记录两道题目:

第一题:计算二叉树的深度,两行递归即可搞定。

public static int level(Node root) {if (root == null)return 0;return level(root.left) + 1 > level(root.right) + 1 ? level(root.left) + 1: level(root.right) + 1;}

第二题:层序遍历一颗二叉树,用广度优先搜索的思想,使用一个队列来按照层的顺序存放节点。

public static void levelTrav(Node root) {if (root == null)return;Queue<Node> q = new ArrayDeque<Node>();q.add(root);Node cur;while (!q.isEmpty()) {cur = q.peek();System.out.print(cur.value + " ");if (cur.left != null)q.add(cur.left);if (cur.right != null)q.add(cur.right);q.poll();}}


0 0
原创粉丝点击