二叉樹系列--層序遍歷(java實現)
阿新 • • 發佈:2019-01-05
記錄兩道題目:
第一題:計算二叉樹的深度,兩行遞迴即可搞定。
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(); } }