[Java] Easy to understand solution using BFS and a HashMap to decorate nodes with their respective depths.


  • 0
    public int minDepth(TreeNode root) {
            if(root == null) return 0;
            
            Map<TreeNode, Integer> hm = new HashMap<TreeNode, Integer>();
            Queue<TreeNode> q = new LinkedList<TreeNode>();
            hm.put(root, 1);
            q.offer(root);
            while(!q.isEmpty()) {
                TreeNode cur = q.poll();
                if(cur.left == null && cur.right == null) return hm.get(cur);
                if(cur.left != null) {
                    hm.put(cur.left, hm.get(cur) + 1);
                    q.offer(cur.left);
                }
                if(cur.right != null) {
                    hm.put(cur.right, hm.get(cur) + 1);
                    q.offer(cur.right);
                }
            }
            return -1;
        }
    

Log in to reply
 

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