记录两道题目:
第一题:计算二叉树的深度,两行递归即可搞定。
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();
}
}