My C code in 0ms by DFS.


  • 0
    W
    int* rightSideView(struct TreeNode* root, int* returnSize) {
    if (root == NULL)
        return NULL;
        
    int* ret = (int*)malloc(sizeof(int)*1000);
    struct TreeNode *stack[100];
    int level[100], top = -1, lvl = 0, rlvl = 0;    // lvl   :   the max level ever searched
    int size = 0;                                   // rlvl  :   the level of current node
    
    stack[++top] = root;
    level[top] = rlvl+1;
    
    while (top != -1) {
        // judge the level;
        if (level[top] > lvl) {
            ret[size++] = stack[top]->val;
            lvl = level[top];
        }
        // pop the stack;
        rlvl = level[top];
        root = stack[top];
        top--;
        // push the stack;
        if (root->left != NULL) {
            stack[++top] = root->left;
            level[top] = rlvl+1;
        }
        if (root->right != NULL) {
            stack[++top] = root->right;
            level[top] = rlvl+1;
        }
    }
    
    *returnSize = size;
    return ret;
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.