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;
}
相关推荐
不吃香菜?23 分钟前
贝叶斯算法实战:从原理到鸢尾花数据集分类
算法·分类·数据挖掘
不吃香菜?32 分钟前
逻辑回归之参数选择:从理论到实践
算法·机器学习·逻辑回归
keep intensify1 小时前
【数据结构】- 栈
c语言·数据结构·算法·
小技与小术2 小时前
代码随想录算法训练营day12(二叉树)
数据结构·python·算法
Chrome深度玩家2 小时前
微博安卓版话题热度推荐算法与内容真实性分析
算法·机器学习·推荐算法
Demons_kirit2 小时前
LeetCode LCP40 心算挑战题解
java·数据结构·算法·leetcode·职场和发展
每次的天空3 小时前
Android面试总结之GC算法篇
android·算法·面试
EanoJiang3 小时前
树与二叉树
算法
蒟蒻小袁4 小时前
力扣面试150题--旋转链表
leetcode·链表·面试
鑫—萍5 小时前
C++——入门基础(2)
java·开发语言·jvm·数据结构·c++·算法