题目描述及链接
题解
前序遍历:遇到空结点直接返回,否则先访问该节点,再依次访问左孩子和右孩子。
中序遍历:遇到空结点直接返回,否则先访问左孩子,再访问该节点,最后访问右孩子。
后序遍历:遇到空结点直接返回,否则先依次访问左右孩子,再访问该节点。
这里题目要求把访问结果放在数组中,所以这里先计算二叉树的节点个数来开辟数组。
/**
* 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)
{
return root == NULL ? 0 : TreeSize(root->left) + TreeSize(root->right) + 1;
}
//子函数
void _preorderTraversal(struct TreeNode* root, int* a, int* pi)
{
if(root == NULL)
{
return;
}
a[(*pi)++] = root->val;
_preorderTraversal(root->left, a, pi);
_preorderTraversal(root->right, a, pi);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize){
int size = TreeSize(root);
int* a = malloc(sizeof(int)*size);
int i = 0;
_preorderTraversal(root, a, &i);
*returnSize = size;
return a;
}
/**
* 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)
{
return root == NULL ? 0 : TreeSize(root->left) + TreeSize(root->right) + 1;
}
void _inorderTraversal(struct TreeNode* root, int* a, int* pi)
{
if(root == NULL)
{
return;
}
_inorderTraversal(root->left, a, pi);
a[(*pi)++] = root->val;
_inorderTraversal(root->right, a, pi);
}
int* inorderTraversal(struct TreeNode* root, int* returnSize){
int size = TreeSize(root);
int* a = malloc(sizeof(int)*size);
int i = 0;
_inorderTraversal(root, a, &i);
*returnSize = size;
return a;
}
/**
* 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)
{
return root == NULL ? 0 : TreeSize(root->left) + TreeSize(root->right) + 1;
}
void _postorderTraversal(struct TreeNode* root, int* a, int* pi)
{
if(root == NULL)
{
return;
}
_postorderTraversal(root->left, a, pi);
_postorderTraversal(root->right, a, pi);
a[(*pi)++] = root->val;
}
int* postorderTraversal(struct TreeNode* root, int* returnSize){
int size = TreeSize(root);
int* a = malloc(sizeof(int)*size);
int i = 0;
_postorderTraversal(root, a, &i);
*returnSize = size;
return a;
}
总结
二叉树的前中后序遍历递归写法的区别只是在访问在左右孩子之前、之间还是之后。