程式語言 - LeetCode - C - 199. Binary Tree Right Side View



參考資訊:
https://www.cnblogs.com/grandyang/p/4392254.html

題目:


解答:

/**
 * 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)
{
    int *r = NULL;
    int q_st = 0;
    int q_ep = 0;
    struct TreeNode *q_buf[101] = { 0 };
    
    r = malloc(sizeof(int) * 101);
    *returnSize = 0;

    if (!root) {
        return r;
    }

    q_buf[0] = root;
    q_ep += 1;

    while ((q_ep - q_st) > 0) {
        int cc = 0;
        int s0 = q_st;
        int s1 = q_ep;
        
        r[(*returnSize)++] = q_buf[s1 - 1]->val;

        for (cc = s0; cc < s1; cc++) {
            q_st += 1;

            if (q_buf[cc]->left) {
                q_buf[q_ep++] = q_buf[cc]->left;
            }

            if (q_buf[cc]->right) {
                q_buf[q_ep++] = q_buf[cc]->right;
            }
        }
    }

    return r;
}