第一题 144. 二叉树的前序遍历
这一题是二叉树的前序遍历:根——左——右
这题需要返回一个数组,所以需要创建一个数组空间,这里重新定义了一个专门进行遍历的函数,如果root
不为空的话就使用递归进行操作并把相对应的val
值存到数组中去。
/**
* 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().
*/
void dopreorderTraversal(struct TreeNode* root, int * ret, int* returnSize) {
if(root) {
ret[(*returnSize)++ ] = root->val;
dopreorderTraversal(root->left, ret, returnSize);
dopreorderTraversal(root->right, ret, returnSize);
}
}
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
int * ret = (int *)malloc(sizeof(int) * 101);
*returnSize = 0;
dopreorderTraversal(root, ret, returnSize);
return ret;
}
第二题 94. 二叉树的中序遍历
/**
* 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().
*/
void doinorderTraversal(struct TreeNode* root, int * ret, int* returnSize) {
if(root) {
doinorderTraversal(root->left, ret, returnSize);
ret[(*returnSize)++] = root->val;
doinorderTraversal(root->right, ret, returnSize);
}
}
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
int * ret = (int *)malloc(sizeof(int) * 105);
*returnSize = 0;
doinorderTraversal(root, ret, returnSize);
return ret;
}
第三题 145. 二叉树的后序遍历
/**
* 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().
*/
void dopostorderTraversal(struct TreeNode* root,int * ret, int* returnSize) {
if(root) {
dopostorderTraversal(root->left, ret, returnSize);
dopostorderTraversal(root->right, ret, returnSize);
ret[(*returnSize)++] = root->val;
}
}
int* postorderTraversal(struct TreeNode* root, int* returnSize) {
int * ret = (int *)malloc(sizeof(int) * 101);
*returnSize = 0;
dopostorderTraversal(root, ret, returnSize);
return ret;
}
第四题 226. 翻转二叉树
这一题主要是理解二叉树的翻转,最主要的是直接翻转整个节点,而不仅仅是节点,所以需要将指针传递。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
void swap(struct TreeNode ** left, struct TreeNode ** right) {
struct TreeNode * temp = *left;
*left = *right;
*right = temp;
}
struct TreeNode* invertTree(struct TreeNode* root) {
if(root) {
swap(&root->left, &root->right);
invertTree(root->left);
invertTree(root->right);
}
return root;
}
这是之前九日集训的解题方式,这个相对来说简单些,但是理解二叉树还是上面的更好
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* invertTree(struct TreeNode* root) {
if(root == NULL) return NULL;
struct TreeNode* left = invertTree(root->left);
struct TreeNode* right = invertTree(root->right);
root->left = right;
root->right = left;
return root;
}