Right View of a Binary Tree - Iterative Approach
Visualization Player
Problem Statement
Examples
Solution
Algorithm Steps
Code
C
C++
Python
Java
JS
Go
Rust
Kotlin
TS
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
TreeNode* createNode(int val) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = node->right = NULL;
return node;
}
int* rightSideView(TreeNode* root, int* returnSize) {
if (!root) {
*returnSize = 0;
return NULL;
}
int* result = malloc(100 * sizeof(int));
TreeNode** queue = malloc(100 * sizeof(TreeNode*));
int front = 0, rear = 0, resIndex = 0;
queue[rear++] = root;
while (front < rear) {
int levelSize = rear - front;
for (int i = 0; i < levelSize; i++) {
TreeNode* node = queue[front++];
if (i == levelSize - 1)
result[resIndex++] = node->val;
if (node->left) queue[rear++] = node->left;
if (node->right) queue[rear++] = node->right;
}
}
*returnSize = resIndex;
free(queue);
return result;
}
int main() {
TreeNode* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->right = createNode(5);
root->right->right = createNode(4);
int size;
int* view = rightSideView(root, &size);
printf("Right view: ");
for (int i = 0; i < size; i++) printf("%d ", view[i]);
printf("\n");
free(view);
return 0;
}
Comments
Loading comments...