Given 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.
For example:
Given the following binary tree,
1 <--- / \ 2 3 <--- \ \ 5 4 <---
You should return [1, 3, 4]
.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
#define MAX_LENGTH 10000
int* rightSideView(struct TreeNode* root, int* returnSize) {
int *res;
if (root == NULL) {
*returnSize = 0;
res = (int *) malloc(sizeof(int));
return res;
}
// 队列
struct TreeNode * queue[MAX_LENGTH];
// 当前队首
int head = 0;
int tail = 0;
//记住每一层入队的个数
int counts_layer;
// 记录 树的高度
int h = 0;
// 记录结果
int res_tmp[MAX_LENGTH];
// 根入队
queue[tail++] = root;
counts_layer = 1;
struct TreeNode * tmp;
while(tail - head != 0) {
int i;
int counts = 0;
// 记录最右边的数
res_tmp[h++] = queue[head + counts_layer - 1]->val;
// 这一层所有的元素
for (i = counts_layer; i > 0; --i) {
tmp = queue[head++];
// 把所有的出队列的元素的孩子如队列
if (tmp->left) {
queue[tail++] = tmp->left;
++counts;
}
if (tmp->right) {
queue[tail++] = tmp->right;
++counts;
}
}
counts_layer = counts;
}
*returnSize = h;
res = (int *) malloc(sizeof(int) * h);
memcpy(res, res_tmp, sizeof(int) * h);
return res;
}
学习笔记:
1. 只要思路清晰,就不怕出错
2. 思路:本题其实求解二叉树每一层最右边的一个数
3. 很自然我们会将每一层的节点入队列,记录最后一个节点的数字