The key insight is to use systematic tree traversal (BFS or DFS) combined with calculated spacing to create a visually readable tree display. The level-order formatting approach processes each tree level systematically with consistent indentation. Time: O(n), Space: O(w) where w is maximum tree width.
Common Approaches
✓
Level-Order Formatting
⏱️ Time: O(n)
Space: O(w)
Traverse the tree level by level using BFS queue, formatting each level with proper indentation and spacing between nodes.
Recursive String Building
⏱️ Time: O(n × w × h)
Space: O(w × h)
Recursively traverse the tree and build a 2D character grid to represent the tree structure. Calculate positions for each node and draw connecting lines manually.
Level-Order Formatting — Algorithm Steps
Step 1: Use BFS queue to process nodes level by level
Step 2: Calculate indentation based on tree height and level
Step 3: Format each level with consistent spacing
Step 4: Build output string line by line
Visualization
Tap to expand
Step-by-Step Walkthrough
1
BFS Traversal
Use queue to visit nodes level by level
2
Calculate Spacing
Determine indentation and spacing based on tree height
3
Format Levels
Build each level string with proper spacing
4
Combine Output
Join all formatted levels into final result
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
struct TreeNode* createNode(int val) {
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
int getHeight(struct TreeNode* node) {
if (!node) return 0;
int leftHeight = getHeight(node->left);
int rightHeight = getHeight(node->right);
return 1 + (leftHeight > rightHeight ? leftHeight : rightHeight);
}
char* solution(struct TreeNode* root) {
if (!root) {
char* result = (char*)malloc(1);
result[0] = '\0';
return result;
}
int height = getHeight(root);
char* result = (char*)malloc(10000);
strcpy(result, "");
struct TreeNode* queue[1000];
int levels[1000];
int front = 0, rear = 0;
queue[rear] = root;
levels[rear] = 0;
rear++;
int currentLevel = 0;
char levelStr[1000] = "";
int nodeCount = 0;
while (front < rear) {
struct TreeNode* node = queue[front];
int level = levels[front];
front++;
if (level != currentLevel) {
if (strlen(levelStr) > 0) {
// Add indentation
for (int i = 0; i < (height - currentLevel) * 2; i++) {
char temp[10000];
strcpy(temp, result);
strcpy(result, " ");
strcat(result, temp);
}
strcat(result, levelStr);
strcat(result, "\n");
}
strcpy(levelStr, "");
currentLevel = level;
nodeCount = 0;
}
if (nodeCount > 0) {
strcat(levelStr, " ");
}
char nodeStr[20];
sprintf(nodeStr, "%d", node->val);
strcat(levelStr, nodeStr);
nodeCount++;
if (node->left || node->right) {
if (node->left) {
queue[rear] = node->left;
levels[rear] = level + 1;
rear++;
}
if (node->right) {
queue[rear] = node->right;
levels[rear] = level + 1;
rear++;
}
}
}
if (strlen(levelStr) > 0) {
for (int i = 0; i < (height - currentLevel) * 2; i++) {
char temp[10000];
strcpy(temp, result);
strcpy(result, " ");
strcat(result, temp);
}
strcat(result, levelStr);
}
return result;
}
struct TreeNode* buildTreeFromArray(int* arr, int size) {
if (size == 0 || arr[0] == -1) return NULL;
struct TreeNode* root = createNode(arr[0]);
struct TreeNode* queue[1000];
int front = 0, rear = 0;
queue[rear++] = root;
int i = 1;
while (front < rear && i < size) {
struct TreeNode* node = queue[front++];
if (i < size && arr[i] != -1) {
node->left = createNode(arr[i]);
queue[rear++] = node->left;
}
i++;
if (i < size && arr[i] != -1) {
node->right = createNode(arr[i]);
queue[rear++] = node->right;
}
i++;
}
return root;
}
int main() {
char input[1000];
fgets(input, sizeof(input), stdin);
input[strcspn(input, "\n")] = 0;
int arr[100];
int size = 0;
char* token = strtok(input + 1, ",]");
while (token != NULL) {
while (*token == ' ') token++;
if (strstr(token, "null")) {
arr[size++] = -1;
} else {
arr[size++] = atoi(token);
}
token = strtok(NULL, ",]");
}
struct TreeNode* root = buildTreeFromArray(arr, size);
char* result = solution(root);
printf("%s", result);
free(result);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(n)
Visit each node exactly once during BFS traversal
n
2n
✓ Linear Growth
Space Complexity
O(w)
Queue stores at most w nodes (maximum width of tree level)
n
2n
✓ Linear Space
23.1K Views
MediumFrequency
~30 minAvg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.