Every day a leetcode
递归实现二叉树的前、中、后序遍历。
前序遍历
题目来源:144. 二叉树的前序遍历
代码:
/**
* 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().
*/
#define MAX_NODE_SIZE 100
void preOrder(struct TreeNode* root,int* ans,int* ansSize)
{
if(root == NULL) return;
ans[(*ansSize)++]=root->val;
preOrder(root->left,ans,ansSize);
preOrder(root->right,ans,ansSize);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize){
*returnSize=0;
int* ans=malloc(MAX_NODE_SIZE*sizeof(int));
preOrder(root,ans,returnSize);
return ans;
}
结果:
中序遍历
题目来源: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().
*/
#define MAX_NODE_SZIE 100
void inOrder(struct TreeNode* root,int* ans,int* ansSize)
{
if(root == NULL) return;
inOrder(root->left,ans,ansSize);
ans[(*ansSize)++]=root->val;
inOrder(root->right,ans,ansSize);
}
int* inorderTraversal(struct TreeNode* root, int* returnSize){
*returnSize=0;
int *ans=malloc(MAX_NODE_SZIE*sizeof(int));
inOrder(root,ans,returnSize);
return ans;
}
结果:
后序遍历
题目来源: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().
*/
#define MAX_NODE_SZIE 100
void postOrder(struct TreeNode* root,int* ans,int* ansSize)
{
if(root == NULL) return;
postOrder(root->left,ans,ansSize);
postOrder(root->right,ans,ansSize);
ans[(*ansSize)++]=root->val;
}
int* postorderTraversal(struct TreeNode* root, int* returnSize){
*returnSize=0;
int *ans=malloc(MAX_NODE_SZIE*sizeof(int));
postOrder(root,ans,returnSize);
return ans;
}
结果: