A Iterative BFS C# Solution with 2 Queues


  • 0
    L
    public int MinDepth(TreeNode root) {
        if(root == null) return 0;
        Queue<TreeNode> queue = new Queue<TreeNode>();
        Queue<int> queueLevel = new Queue<int>();
        queue.Enqueue(root);
        queueLevel.Enqueue(1);
        while(queue.Count != 0)
        {
            TreeNode tmp = queue.Dequeue();
            int level = queueLevel.Dequeue();
            if(tmp.left == null && tmp.right == null) return level;
            else
            {
                level++;
                if(tmp.left != null)
                {
                    queue.Enqueue(tmp.left);
                    queueLevel.Enqueue(level);
                }
                if(tmp.right != null)
                {
                    queue.Enqueue(tmp.right);
                    queueLevel.Enqueue(level);
                }
            }
        }
        return 0;
    }

  • 0
    T

    Nice solution. Notice that you're taking a additional queue only for recording the height(level) of the accessed TreeNode. I think it's better to use queue<pair<TreeNode*, int>> (TreeNode* node, int height) instead :)


Log in to reply
 

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