Share my 3 ms C solutions


  • 0

    more codes see: https://github.com/lightmen/leetcode.git

    /*
    1、分层遍历二叉树;
    2、并用一个队列queue保存遍历出来的TreeNode元素;
    3、level保存当前遍历层的TreeNode数;
    4、count记录下一层的TreeNode数;
    */

    int *rightSideView(struct TreeNode *root, int *n) {

    int order = 6;
    int *ret;
    struct TreeNode *queue[100],*tmp;
    int front,tail;
    int level = 0;
    int count;
    int i;
    
    *n = 0;
    ret = (int *)malloc(sizeof(int) * (1 << order));
    front = -1;
    tail = -1;
    
    if(root){
        tail++;
        queue[tail] = root;
        level = 1;
    }
    while(front != tail){
        i = 0;
        count = 0;
        while(i < level){
            i++;
            front = (front + 1) % 100;
            tmp = queue[front];
            ret[*n] = tmp->val;
            if(tmp->left){
                tail = (tail + 1) % 100;
                queue[tail] = tmp->left;
                count++;
            }
            if(tmp->right){
                tail = (tail + 1) % 100;
                queue[tail] = tmp->right;
                count++;
            }
        }
        level = count;
        (*n)++;
        if(*n == (1 << order)){
            order <<= 1;
            ret = realloc(ret,1 << order);
        }
    }
    return ret;
    

    }


Log in to reply
 

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