Count Complete Tree Nodes

Solution Code
class Solution:
    def countNodes(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        
        leftDepth = self.getDepth(root, True)
        rightDepth = self.getDepth(root, False)
        
        if leftDepth == rightDepth:
            return (1 << leftDepth) - 1
        
        return 1 + self.countNodes(root.left) + self.countNodes(root.right)
    
    def getDepth(self, node: Optional[TreeNode], isLeft: bool) -> int:
        depth = 0
        while node:
            depth += 1
            node = node.left if isLeft else node.right
        return depth

Time Complexity

O(log^2 n)

Space Complexity

O(log n)