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;
}
相关推荐
And_Ii2 分钟前
LeetCode 3397. 执行操作后不同元素的最大数量
数据结构·算法·leetcode
额呃呃8 分钟前
leetCode第33题
数据结构·算法·leetcode
隐语SecretFlow14 分钟前
【隐语SecretFlow用户案例】亚信科技构建统一隐私计算框架探索实践
科技·算法·安全·隐私计算·隐私求交·开源隐私计算
dragoooon3418 分钟前
[优选算法专题四.前缀和——NO.27 寻找数组的中心下标]
数据结构·算法·leetcode
少许极端24 分钟前
算法奇妙屋(七)-字符串操作
java·开发语言·数据结构·算法·字符串操作
小龙报1 小时前
《算法通关指南---C++编程篇(2)》
c语言·开发语言·数据结构·c++·程序人生·算法·学习方法
金宗汉1 小时前
《宇宙递归拓扑学:基于自指性与拓扑流形的无限逼近模型》
大数据·人工智能·笔记·算法·观察者模式
YY_TJJ3 小时前
算法题——贪心算法
算法·贪心算法
C++ 老炮儿的技术栈3 小时前
include″″与includ<>的区别
c语言·开发语言·c++·算法·visual studio
RainbowC03 小时前
GapBuffer高效标记管理算法
android·算法