C# Iterative Solution using Queue Accepted


  • 0
    S
    public int MinDepth(TreeNode root) 
    {
        if (root == null)
            return 0;
        return MinHeightOfTreeItr(root);
    }
    
    private int MinHeightOfTreeItr(TreeNode rootNode)
    {
        if (rootNode == null)
            return 0;
    
        int levelCnt = 0;
        Queue<TreeNode> parentQ = new Queue<TreeNode>();
        Queue<TreeNode> levelQ = new Queue<TreeNode>();
    
        parentQ.Enqueue(rootNode);
    
        while (parentQ.Count > 0)
        {
            TreeNode currNode = parentQ.Dequeue();
    
            if (currNode.left == null && currNode.right == null)
                return ++levelCnt;
    
            if (currNode.left != null)
                levelQ.Enqueue(currNode.left);
    
            if (currNode.right != null)
                levelQ.Enqueue(currNode.right);
    
            if (parentQ.Count == 0)
            {
                parentQ = levelQ;
                levelQ = new Queue<TreeNode>();
                ++levelCnt;
            }
        }
            
        return -1;
    }

Log in to reply
 

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