102. 二叉树的层序遍历
题目链接
解
const int max = 10000;
struct queue {
int front, back;
struct TreeNode *array[10000];
};
int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes) {
struct queue *que = (struct queue *)malloc(sizeof(*que));
struct TreeNode *node = root;
int **ans = (int **)malloc(sizeof(int*) * max);
int row = 0, col;
*returnColumnSizes = (int *)malloc(sizeof(int) * max);
memset(que, 0, sizeof(*que));
que->front = que->back = 0;
memset(ans, 0, sizeof(int*) * max);
*returnSize = 0;
if (root == NULL) {
return ans;
}
que->array[que->back++] = node;
while (que->back != que->front) {
col = 0;
ans[row] = (int *)malloc(sizeof(int) * max);
memset(ans[row], 0, sizeof(int) * max);
int cur = que->back;
while (cur != que->front) {
node = que->array[que->front];
ans[row][col++] = node->val;
if (node->left != NULL) que->array[que->back++] = node->left;
if (node->right != NULL) que->array[que->back++] = node->right;
que->front++;
}
(*returnColumnSizes)[row] = col;
row++;
}
*returnSize = row;
return ans;
}
226. 翻转二叉树
题目链接
解: 递归
struct TreeNode* invertTree(struct TreeNode* root) {
if (root == NULL) return root;
struct TreeNode *tmp = root->left;
root->left = root->right;
root->right = tmp;
invertTree(root->left);
invertTree(root->right);
return root;
}
101. 对称二叉树
题目链接
解: 递归
bool compare(struct TreeNode *left, struct TreeNode *right) {
if (left == NULL && right != NULL) return false;
else if (left != NULL && right == NULL) return false;
else if (left == NULL && right == NULL) return true;
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) {
if (root == NULL) return true;
return compare(root->left, root->right);
}