199. Binary Tree Right Side View
Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example 1:
Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]
Example 2:
Input: root = [1,null,3]
Output: [1,3]
Example 3:
Input: root = []
Output: []
Constraints:
- The number of nodes in the tree is in the range [0, 100].
- -100 <= Node.val <= 100
From: LeetCode
Link: 199. Binary Tree Right Side View
Solution:
Ideas:
- Use a queue to keep track of nodes at the current level.
- For each level, enqueue the left and right children of nodes from the previous level.
- For each level, the last node dequeued is the rightmost node and thus visible from the right side.
- Store the value of the rightmost node for each level in the result.
Code:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* rightSideView(struct TreeNode* root, int* returnSize) {
if (!root) {
*returnSize = 0;
return NULL;
}
// Define a queue for BFS
struct TreeNode* queue[101];
int front = 0, rear = 0;
queue[rear++] = root;
int* result = (int*)malloc(100 * sizeof(int));
*returnSize = 0;
while (front < rear) {
int levelSize = rear - front;
for (int i = 0; i < levelSize; ++i) {
struct TreeNode* currentNode = queue[front++];
// If this is the last node in the current level, add its value to the result
if (i == levelSize - 1) {
result[(*returnSize)++] = currentNode->val;
}
// Enqueue left and right children
if (currentNode->left) queue[rear++] = currentNode->left;
if (currentNode->right) queue[rear++] = currentNode->right;
}
}
return result;
}