• + 0 comments
    c# csharp
    
    solution that doesn't use recursion
    
    private static int getHeight(Node root)
    {
        if (root == null)
        {
            return -1; // height of empty tree is -1
        }
    
        Queue<Node> queue = new Queue<Node>();
        queue.Enqueue(root);
        int height = -1;
    
        while (queue.Count > 0)
        {
            int nodeCount = queue.Count;  // Number of nodes at the current level
            height++;
    
            // Process each node at the current level
            while (nodeCount > 0)
            {
                Node node = queue.Dequeue();
    
                // Enqueue left and right children of the current node
                if (node.left != null)
                {
                    queue.Enqueue(node.left);
                }
                if (node.right != null)
                {
                    queue.Enqueue(node.right);
                }
    
                nodeCount--;
            }
        }
    
        return height;
    }