102.二叉树的层序遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume
* caller calls free().
*/
int** levelOrder(struct TreeNode* root, int* returnSize,
int** returnColumnSizes) {
int test=0;
int** res = (int**)calloc(10000, sizeof(int*));
*returnColumnSizes=(int*)calloc(10000,sizeof(int));
*returnSize = 0;
struct TreeNode **my_queue = (struct TreeNode**)calloc(10000,sizeof(struct TreeNode*));
//存储的指针而不是值,不然无法遍历后续结点
//是struct TreeNode *而不是int*
int front = 0, rear = 0;
if (root) {
my_queue[rear] = root;
rear = (rear + 1) % 10000;
}
while (front != rear) { //栈非空时
int size = (rear - front) % 10000;//栈内元素数量
//printf(" size=%d\n",size);
int* arr = (int*)calloc(size, sizeof(int));
// printf(" size=%d\n",size);
for (int i = 0; i < size; i++) {//将队列中现存所有元素出队并压入他们的孩子结点指针
// 这里一定要使用固定大小size,不要使用que.size(),因为que.size是不断变化的
struct TreeNode * p=my_queue[front];
//应该放在for内部,不能放在while,不然无法正确遍历后续结点
//printf("my_queue[front]->val=%d\n",my_queue[front]->val);
arr[i] = my_queue[front]->val; //出队元素
// printf(" front=%d,arr[i]=%d,i=%d,p->val=%d,here \n",front,arr[i],i,p->val);
front = (front + 1) % 10000;
if (p->left) {//孩子非空则入队
my_queue[rear] = p->left;
// printf(" rear=%d ",rear);
rear = (rear + 1) % 10000;
}
if (p->right) {
my_queue[rear] = p->right;
//printf(" rear=%d \n",rear);
rear = (rear + 1) % 10000;
}
}
(*returnColumnSizes)[*returnSize]=size;//要加()不然优先级会出问题
res[(*returnSize)++]=arr;
// printf("*returnSize=%d\n",*returnSize);
//printf("test=%d\n 1 ",test++);
}
//printf("*returnSize=%d\n",*returnSize);
return res;
}
226.翻转二叉树
//左右孩子交换的是指针不是 数值
//优先使用前/后序 ,中序较麻烦
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* invertTree(struct TreeNode* root) {
if(!root) return root;
struct TreeNodeq* temp=root->left;
root->left=root->right;
root->right=temp;
invertTree(root->left);
invertTree(root->right);
return root;
}
101. 对称二叉树
//对称:左右子树可以相互翻转
//只能使用后序:只有后序遍历才能将左右孩子是否相等的信息返回给上一层结点,上一层结点要最后处理
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool compare(struct TreeNode* left,struct TreeNode* right){
//终止条件
if(!left&&!right) return true;//左右均为空
else if(!left||!right) return false;//仅一个为空
else if(left->val!=right->val) return false;
//左右结点值相同 继续遍历下一层结点
bool outside=compare(left->left,right->right);//对比两子树外层结点是否相同;
bool inside=compare(left->right,right->left);//对比两子树内层结点是否相同;
return outside&&inside;//中
}
bool isSymmetric(struct TreeNode* root) {
return compare(root->left,root->right);
}