【C语言】二叉树前序中序后序遍历详解!!!内附算法好题初阶(每日小细节021)

文章详细介绍了二叉树的三种遍历方法:前序遍历(根-左-右),中序遍历(左-根-右),后序遍历(左-右-根),并提供了C语言的递归实现代码示例。此外,文章强调了每日学习算法的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

二叉树三种遍历方式时刻牢记,所谓的前中后就是根的位置

前序:->左子树->右子树

中序:左子树->->右子树

后序:左子树->右子树->

每日小细节新增算法好题合集,现在是初阶,每天会更新至少两道题目,感兴趣的小伙伴赶紧关注收藏不迷路哦

花费几分钟就能积累一种新的解题思路多是一件美事啊~

 

目录

1.二叉树前序遍历

2.二叉树中序遍历

3.二叉树后序遍历


1.二叉树前序遍历

二叉树的前序遍历 

首先介绍一下二叉树的三种遍历方式:前序,中序,后序

前序:遍历顺序为 ->左子树->右子树

 

按顺序递归下去,左子树全部走完才开始遍历右子树

所以就是

 

 每一个方框内都能清楚看到 根-左子树-右子树 的样子

/**
 * 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 preorder(struct TreeNode* root,int* res,int*resSize){
if(root==NULL){
    return ;
}
res[(*resSize)++]=root->val;
preorder(root->left,res,resSize);
preorder(root->right,res,resSize);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize)
{
    int* res=(int*)malloc(sizeof(int)*200);
    *returnSize=0;
    preorder(root,res,returnSize);
    return res;
}*/
void preorder(struct TreeNode* root,int* res,int*resSize){
if(root==NULL){
    return ;
}
res[(*resSize)++]=root->val;
preorder(root->left,res,resSize);
preorder(root->right,res,resSize);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize)
{
    int* res=(int*)malloc(sizeof(int)*101);
    *returnSize=0;
    preorder(root,res,returnSize);
    return res;
}

 这个前序遍历的题目就自己开辟一块空间,然后把要返回的数组长度先置成0(和新数组的下标一致,这样就可以轻松找到节点个数),然后按照前面说的顺序递归即可


2.二叉树中序遍历

二叉树的中序遍历

中序:左子树->->右子树

 

其中黑色的圈是根节点

 void inorder(struct TreeNode* root,int* res,int*resSize){
if(root==NULL){
    return ;
}
inorder(root->left,res,resSize);
res[(*resSize)++]=root->val;
inorder(root->right,res,resSize);
}
int* inorderTraversal(struct TreeNode* root, int* returnSize){
int* res=(int*)malloc(sizeof(int)*101);
    *returnSize=0;
    inorder(root,res,returnSize);
    return res;
}

 思路和上一题完全一样,遍历递归时候顺序调整一下就好了


 

3.二叉树后序遍历

二叉树的后序遍历

后序:左子树->右子树->

遍历过程和前面类似

 

 void postorder(struct TreeNode* root,int* res,int*resSize){
if(root==NULL){
    return ;
}
postorder(root->left,res,resSize);
postorder(root->right,res,resSize);
res[(*resSize)++]=root->val;
} 
int* postorderTraversal(struct TreeNode* root, int* returnSize){
  int* res=(int*)malloc(sizeof(int)*101);
    *returnSize=0;
   postorder(root,res,returnSize);
    return res;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值