LeetCode中的前中后序遍历OJ题
对于二叉树部分LeetCode还有很多简单但是好的题目:
LeetCode关于单值、翻转、对称、最大深度、另一颗树的子树二叉树题目解析链接: link.
LeetCode关于平衡二叉树和层序遍历解析链接: link.
1. LeetCode第144题—二叉树的前序遍历
链接: link.
/**
* 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().
*/
//因为你需要知道在开辟空间大小的时候,开辟多大才行,所以要算结点的个数
int TreeSize(struct TreeNode* root)
{
if(root == NULL)
return 0;
else
return 1+TreeSize(root->left) + TreeSize(root->right);
}
//前序遍历
void _preorderTraversal(struct TreeNode* root,int* array,int* pi)
{
if(root == NULL)
return;
array[(*pi)++] = root->val;
_preorderTraversal(root->left,array,pi); //这里的pi是传过来的指针,可以直接的使用
_preorderTraversal(root->right,array,pi);
}
//这里值得注意的就是在传i的时候一定要传地址,因为只有传值才能做到在同一个i上++的效果
int* preorderTraversal(struct TreeNode* root, int* returnSize){
int size = TreeSize(root);
int* array = (int*)malloc(sizeof(int)*size);
int i = 0;
_preorderTraversal(root,array,&i); //思考题目就明白他需要你把结点的值都放在一个数组里面
*returnSize = size;
return array;
}
2. LeetCode第94题—二叉树的中序遍历
链接: link.
/**
* 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().
*/
int TreeSize(struct TreeNode* root)
{
if(root == NULL)
return 0;
else
return 1+TreeSize(root->left)+TreeSize(root->right);
}
//左子树 根 右子树
void _inorderTraversal(struct TreeNode* root,int* array,int* pi)
{
if(root == NULL)
return;
_inorderTraversal(root->left,array,pi);
array[(*pi)++] = root->val;
_inorderTraversal(root->right,array,pi);
}
int* inorderTraversal(struct TreeNode* root, int* returnSize){
int size = TreeSize(root);
int* array = (int*)malloc(sizeof(int)*size);
int i = 0;
_inorderTraversal(root,array,&i);
*returnSize = size;
return array;
}
3. LeetCode第145题—二叉树的后序遍历
链接: link.
/**
* 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().
*/
int TreeSize(struct TreeNode* root)
{
if(root == NULL)
return 0;
else
return 1+TreeSize(root->left)+TreeSize(root->right);
}
void _postorderTraversal(struct TreeNode* root,int* array,int* pi)
{
if(root == NULL)
return;
_postorderTraversal(root->left,array,pi);
_postorderTraversal(root->right,array,pi);
array[(*pi)++] = root->val;
}
int* postorderTraversal(struct TreeNode* root, int* returnSize){
int size = TreeSize(root);
int* array = (int*)malloc(sizeof(int)*size);
int i = 0;
_postorderTraversal(root,array,&i);
*returnSize = size;
return array;
}