C数据结构-队列

leetcode102题,二叉树的层次遍历
leetcode199题,二叉树的右视图
队列的思路如下:
1、有head、tail
2、入队靠tail,出队靠head
3、如果每轮需要出队,那么把tail-head存下来,做一个for循环!!!非常重要

#define MAXLEN 1000

int Enqueue(struct TreeNode* root, int tail, struct TreeNode * que[]) {
	if (root == NULL) {
		return tail;
	}
	que[tail++] = root;
	return tail;
}

int* rightSideView(struct TreeNode* root, int* returnSize) {
	int tmp[MAXLEN];
	struct TreeNode *queue[MAXLEN];
	int i, currwide, head = 0, tail = 0, count = 0;
	if (root == NULL) {
        *returnSize = 0;
		return NULL;
	}
	queue[tail++] = root;
	while (head < tail) {
		currwide = tail - head;
		for (i = 0; i < currwide; i++) {
			tail = Enqueue(queue[head]->left, tail, queue);
			tail = Enqueue(queue[head]->right, tail, queue);
			if (i == currwide - 1) {
				tmp[count++] = queue[head]->val;
			}
			head++;
		}
	}

	int *ret = (int *)malloc(sizeof(int)*count);
	memcpy(ret, tmp, sizeof(int)*count);
	*returnSize = count;
	return ret;
}
int gets_tree_row(struct TreeNode* root) {
    if (root == NULL) {
        return 0;
    }
    int a = gets_tree_row(root->left);
    int b = gets_tree_row(root->right);
    return a>b ? (a+1) : (b+1);
}

int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes){
    
    *returnSize = 0;
    if (root == NULL) {
        return NULL;
    }
    
    * returnSize = gets_tree_row(root);
    int row = *returnSize;

    int head, tail, tmptail;
    tail = head = 0;

    struct TreeNode * queue[1000];
    struct TreeNode * tmp;
    int ** res = (int ** )malloc(sizeof(int *) * row);
    *returnColumnSizes = (int*)malloc(sizeof(int) * row);
    queue[tail++] = root; //put root in queue
    int i = 0, j = 0;
    while(head < tail){
        int column = tail - head;
        res[i] = (int *) malloc(sizeof(int) * column);
        (*returnColumnSizes)[i] = column;
        for(j = 0;j < column;j++ ) {
            tmp = queue[head++];
            if (tmp->left != NULL) {
                queue[tail++] = tmp->left;
            }
            if (tmp->right != NULL) {
                queue[tail++] = tmp->right;
            }
            res[i][j] = tmp->val;
        }
        i++;        
    }

    return res;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值