My BFS solution


  • 0
    F

    BFS solution

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int minDepth(TreeNode root) {
            if (root == null) {
                return 0;
            }
            int depth = 1;
            Queue<TreeNode> que = new LinkedList<>();
            que.add(root);
            
            while (!que.isEmpty()) {
                int size = que.size();
                for (int i = 0; i < size; i++) {
                    TreeNode curr = que.poll();
                    if (curr.left == null && curr.right == null) {
                        return depth;
                    }
                    if (curr.left != null) {
                        que.add(curr.left);
                    }
                    if (curr.right != null) {
                        que.add(curr.right);
                    }
                }
                depth++;
            }
            return depth;
        }
    }
    
    

Log in to reply
 

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