BFS solution for Java


  • 0
    Z
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public int minDepth(TreeNode root) {
            Queue<QueueNode> queue = new LinkedList<QueueNode>();
            if(root==null)
                return 0;
            queue.add(new QueueNode(root, 1));
            while(!queue.isEmpty()) {
                QueueNode top = queue.poll();
                if(top.n.left==null && top.n.right==null) 
                    return top.dep;
                if(top.n.left!=null) 
                    queue.add(new QueueNode(top.n.left, top.dep+1));
                if(top.n.right!=null)
                    queue.add(new QueueNode(top.n.right, top.dep+1));
            }
            return -1;
        }
    }
    
    class QueueNode {
        public TreeNode n;
        public int dep;
        public QueueNode(TreeNode nn, int depth) {
            n=nn;
            dep=depth;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.