199. Binary Tree Right Side View

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. 很自然我们会将每一层的节点入队列,记录最后一个节点的数字







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值