Imagine exploring a family tree where some children are only children while others have siblings. In this binary tree problem, we need to identify all the lonely nodes - those that are the only child of their parent.
A lonely node is defined as a node that has no siblings (i.e., it's either the only left child or the only right child of its parent). The root node is never considered lonely since it has no parent.
Goal: Given the root of a binary tree, return an array containing the values of all lonely nodes. The order of the result doesn't matter.
Example: In a tree where node 5 has only a left child (node 3), then node 3 is lonely. Similarly, if node 7 has only a right child (node 9), then node 9 is lonely.
Input & Output
example_1.py — Basic Tree
$Input:root = [1,2,3,null,4]
›Output:[4]
💡 Note:Node 2 has only one child (node 4), so node 4 is lonely. Node 3 has no children and node 1 has two children, so no other nodes are lonely.
The optimal solution uses a single DFS traversal to identify lonely nodes in O(n) time. During traversal, we check each parent node to see if it has exactly one child (either only left or only right), and add that child to our result. This approach is much more efficient than checking each node's parent separately, avoiding the O(n²) complexity of naive approaches.
Common Approaches
✓
Bfs
⏱️ Time: N/A
Space: N/A
Optimized DFS (Single Pass)
⏱️ Time: O(n)
Space: O(h)
This optimal approach performs a single depth-first traversal of the tree. During the traversal, we check each parent node to see if it has exactly one child, and if so, we add that child to our result list. This is much more efficient than multiple traversals.
Algorithm Steps — Algorithm Steps
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <ctype.h>
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
struct QueueNode {
struct TreeNode* treeNode;
struct QueueNode* next;
};
struct Queue {
struct QueueNode* front;
struct QueueNode* rear;
int size;
};
struct Queue* createQueue() {
struct Queue* q = (struct Queue*)malloc(sizeof(struct Queue));
q->front = q->rear = NULL;
q->size = 0;
return q;
}
void enqueue(struct Queue* q, struct TreeNode* node) {
struct QueueNode* temp = (struct QueueNode*)malloc(sizeof(struct QueueNode));
temp->treeNode = node;
temp->next = NULL;
if (q->rear == NULL) {
q->front = q->rear = temp;
} else {
q->rear->next = temp;
q->rear = temp;
}
q->size++;
}
struct TreeNode* dequeue(struct Queue* q) {
if (q->front == NULL) return NULL;
struct QueueNode* temp = q->front;
struct TreeNode* node = temp->treeNode;
q->front = q->front->next;
if (q->front == NULL) q->rear = NULL;
free(temp);
q->size--;
return node;
}
int* solution(struct TreeNode* root, int* returnSize) {
*returnSize = 0;
if (!root) return NULL;
int* result = (int*)malloc(1000 * sizeof(int));
struct Queue* queue = createQueue();
enqueue(queue, root);
while (queue->size > 0) {
int levelSize = queue->size;
int levelMax = INT_MIN;
// Process all nodes at current level
for (int i = 0; i < levelSize; i++) {
struct TreeNode* node = dequeue(queue);
if (node->val > levelMax) {
levelMax = node->val;
}
// Add children to queue for next level
if (node->left) enqueue(queue, node->left);
if (node->right) enqueue(queue, node->right);
}
result[(*returnSize)++] = levelMax;
}
free(queue);
return result;
}
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;
}
struct TreeNode* buildTree(char** tokens, int tokenCount) {
if (tokenCount == 0 || strcmp(tokens[0], "null") == 0) return NULL;
struct TreeNode* root = createNode(atoi(tokens[0]));
struct TreeNode** queue = (struct TreeNode**)malloc(10000 * sizeof(struct TreeNode*));
int front = 0, rear = 0;
queue[rear++] = root;
int i = 1;
while (front < rear && i < tokenCount) {
struct TreeNode* node = queue[front++];
if (i < tokenCount && strcmp(tokens[i], "null") != 0) {
node->left = createNode(atoi(tokens[i]));
queue[rear++] = node->left;
}
i++;
if (i < tokenCount && strcmp(tokens[i], "null") != 0) {
node->right = createNode(atoi(tokens[i]));
queue[rear++] = node->right;
}
i++;
}
free(queue);
return root;
}
void parseArray(const char* str, int* arr, int* size) {
*size = 0;
const char* p = str;
while (*p && *p != '[') p++;
if (*p == '[') p++;
while (*p && *p != ']') {
while (*p == ' ' || *p == ',') p++;
if (*p == ']' || *p == '\0') break;
arr[(*size)++] = (int)strtol(p, (char**)&p, 10);
}
}
int main() {
char line[10000];
fgets(line, sizeof(line), stdin);
// Remove newline
line[strcspn(line, "\n")] = 0;
// Remove brackets
char* start = strchr(line, '[');
char* end = strrchr(line, ']');
if (!start || !end) return 1;
start++;
*end = '\0';
// Parse tokens
char** tokens = (char**)malloc(1000 * sizeof(char*));
int tokenCount = 0;
char* token = strtok(start, ",");
while (token) {
// Trim whitespace
while (isspace(*token)) token++;
char* tokenEnd = token + strlen(token) - 1;
while (tokenEnd > token && isspace(*tokenEnd)) *tokenEnd-- = '\0';
tokens[tokenCount] = (char*)malloc(strlen(token) + 1);
strcpy(tokens[tokenCount], token);
tokenCount++;
token = strtok(NULL, ",");
}
struct TreeNode* root = buildTree(tokens, tokenCount);
int returnSize;
int* result = solution(root, &returnSize);
printf("[");
for (int i = 0; i < returnSize; i++) {
if (i > 0) printf(",");
printf("%d", result[i]);
}
printf("]\n");
// Cleanup
for (int i = 0; i < tokenCount; i++) {
free(tokens[i]);
}
free(tokens);
free(result);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
n
2n
✓ Linear Growth
Space Complexity
n
2n
✓ Linear Space
23.8K Views
MediumFrequency
~15 minAvg. Time
892 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.