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;
}