您的位置:首页 > 编程语言 > Java开发

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

2015-09-19 19:52 274 查看
记录两道题目:

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

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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: