C# BFS solution


  • 0
    S
    public int MinDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        Queue<TreeNode> queue = new Queue<TreeNode>();
        int depth = 0;
        TreeNode depthIncNode = root;
        queue.Enqueue(root);
        while (queue.Count > 0) {
            TreeNode node = queue.Dequeue();
            if (node == depthIncNode) {
                depthIncNode = null;
                depth++;
            }
            
            if (node.left == null && node.right == null) {
                // leaf found
                return depth;
            }
            
            if (node.left != null) {
                queue.Enqueue(node.left);
                if (depthIncNode == null) {
                    depthIncNode = node.left;
                }
            }
            if (node.right != null) {
                queue.Enqueue(node.right);
                if (depthIncNode == null) {
                    depthIncNode = node.right;
                }
            }
        }
        return 0;
    }

Log in to reply
 

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