LeetCode | 二叉树的前中后序遍历

LeetCode | 二叉树的前中后序遍历

OJ链接

  • 这里我们使用递归的方法来解决
  • 这里题目还要求我们返回这棵树的根
  • 我们这里需要先算出这个树有多大
  • 然后开辟空间
  • 再进行前序的遍历
c 复制代码
void preorder(struct TreeNode* root,int* a,int* pi)
{
    if(root == NULL)
        return;
    a[(*pi)++] = root->val;

    preorder(root->left,a,pi);
    preorder(root->right,a,pi);
}
int TreeSize(struct TreeNode* root)
{
    return root == NULL ? 0 : TreeSize(root->left) + TreeSize(root->right) + 1;
}

int* preorderTraversal(struct TreeNode* root, int* returnSize) {
    //计算树有多少个节点
    int n = TreeSize(root);
    *returnSize = n;
    //开辟n个大小
    int* a = malloc(sizeof(int) * n);

    int i = 0;
    //前序遍历
    preorder(root,a,&i);
    return a;
}

  • 这里前序遍历完成后,我们的中序和后序也是一样的,直接CV即可

  • 中序遍历:OJ链接

c 复制代码
int TreeSize(struct TreeNode* root)
{
    return root == NULL ? 0 : TreeSize(root->left) + TreeSize(root->right) + 1;
}

void inorder(struct TreeNode* root,int* a ,int* pi)
{
    if(root == NULL)
        return;
    
    inorder(root->left,a,pi);
    a[(*pi)++] = root->val;
    inorder(root->right,a,pi);
}

int* inorderTraversal(struct TreeNode* root, int* returnSize) {
    int n = TreeSize(root);
    int* a = (int*)malloc(sizeof(int) * n);

    *returnSize = n;
    int i = 0;
    inorder(root,a,&i);

    return a;
}
c 复制代码
int TreeSize(struct TreeNode* root)
{
    return root == NULL ? 0 : TreeSize(root->left) + TreeSize(root->right) + 1;
}

void postorder(struct TreeNode* root,int* a ,int* pi)
{
    if(root == NULL)
        return;
    
    postorder(root->left,a,pi);
    postorder(root->right,a,pi);
    a[(*pi)++] = root->val;

}
int* postorderTraversal(struct TreeNode* root, int* returnSize) {
    int n = TreeSize(root);
    int* a = (int*)malloc(sizeof(int) * n);

    *returnSize = n;
    int i = 0;
    postorder(root,a,&i);

    return a;
}
相关推荐
自由的晚风8 分钟前
脑电波控制设备:基于典型相关分析(CCA)的脑机接口频率精准解码方法
人工智能·经验分享·笔记·算法·matlab·脑机接口·ssvep
小辉同志23 分钟前
146.LRU缓存
c++·算法·链表·缓存·力扣
mzgong1 小时前
DeepSeek-R1深度解读
人工智能·深度学习·算法
Vitalia1 小时前
⭐算法OJ⭐汉明距离【位操作】(C++ 实现)Hamming Distance
开发语言·c++·算法
白云千载尽1 小时前
开源的自动驾驶视觉语言模型标注数据集
算法·机器学习·自动驾驶·ros
无咎.lsy1 小时前
leetcode【面试经典150系列】(一)
数据结构·算法
whltaoin1 小时前
软考数据结构四重奏:软件工程师的线性、树、图、矩阵算法精要
数据结构·算法
AI技术控2 小时前
计算机视觉算法实战——手势识别(主页有源码)
人工智能·算法·计算机视觉
დ旧言~3 小时前
贪心算法五
算法·leetcode·贪心算法·动态规划·推荐算法
m0_461502693 小时前
【贪心算法5】
算法·贪心算法