题目:199.二叉树的右视图
题解
/**
* 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().
*/
#define MAXSIZE 50
typedef struct {
struct TreeNode * tn;
int floor;
} QueueNode,*Queue;
int* rightSideView(struct TreeNode* root, int* returnSize){
if(root == NULL){
*returnSize = 0;
return NULL;
}
//准备树的层序遍历使用的循环队列
int front = 0, rear = 0;
Queue q = (QueueNode*)malloc(sizeof(QueueNode)*MAXSIZE);
//层序遍历数,把每层最后的数保留下来即可
q[rear].tn = root;
q[rear].floor = 1;
rear = (rear + 1) % MAXSIZE;
int* result = (int*)malloc(sizeof(int)*100);
*returnSize = 0;
while(rear != front){ //层序遍历未结束
QueueNode temp = q[front];
front = (front + 1) % MAXSIZE;
if(floor == rear || temp.floor != q[front].floor){
result[(*returnSize)++] = temp.tn->val;
}
if(temp.tn->left != NULL){
q[rear].tn = temp.tn->left;
q[rear].floor = temp.floor + 1;
rear = (rear + 1) % MAXSIZE;
}
if(temp.tn->right != NULL){
q[rear].tn = temp.tn->right;
q[rear].floor = temp.floor + 1;
rear = (rear + 1) % MAXSIZE;
}
}
return result;
}
要点
复习一下二叉树的层序遍历,本题就是把每层的最后一个输出。
取值符号的*的优先级小于自增符号优先级++,因此想通过指针让一个整数值自增的写法是(*returnSize)++。
题目:14.最长公共前缀
题解
char * longestCommonPrefix(char ** strs, int strsSize){
int minSize = 201;
for(int i = 0; i < strsSize; i++){
minSize = strlen(strs[i]) < minSize ? strlen(strs[i]) : minSize;
}
int count = 0;
int flag = 1; //位置都相等的标志。
for(int i = 0; i < minSize; i++){ //比较每个字符串的第i位
char c = strs[0][i];
for(int j = 1; j < strsSize; j++){
if(strs[j][i] != c){
flag = 0;
}
}
if(flag == 0){
break;
}else {
count++;
}
}
if(count == 0){
return "";
}
char* result = (char*)malloc(sizeof(char)*(count+1));
for(int i = 0; i < count; i++){
result[i] = strs[0][i];
}
result[count] = '\0';
return result;
}
要点
为指针分配地址是想多分配一个单位记得加括号。sizeof(int)*(count+1)。
结果仅返回字符串,不返回输出个数时,该字符串要预留一个位置并将该位置指值设置为'\0'。