Wednesday, March 5, 2014

Java Queue in LeetCode Minimum Depth of Binary Tree


Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Solution:

The problem itself is not difficult at all. I would like to summarize the usage of queue in java.

Unlike Stack<E> which is can be used directly(empty(), peek(), pop(), push(E item), search(Object) 0), Queue<E>  (isEmpty(), add()/offer(), remove()/poll(), peek()/element()) is an interface in java.

Simply use LinkedList<E> because LinkedList has methods to support queue behavior and it implements the Queue interface, so a LinkedList can be used as a Queue implmentation by upcasting a LinkedList to a Queue, i.e., 

Queue<TreeNode> queue = LinkedList<TreeNode>();

For this problem, use BFS and an special node to indicate the end of a level (nullNode). The code passed leetcode with only one try.

The most simple method to solve this problem is using recursion, as follows:

No comments:

Post a Comment