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;
}
相关推荐
希望有朝一日能如愿以偿34 分钟前
力扣题解(飞机座位分配概率)
算法·leetcode·职场和发展
Espresso Macchiato42 分钟前
Leetcode 3306. Count of Substrings Containing Every Vowel and K Consonants II
leetcode·滑动窗口·leetcode medium·leetcode 3306·leetcode周赛417
丶Darling.1 小时前
代码随想录 | Day26 | 二叉树:二叉搜索树中的插入操作&&删除二叉搜索树中的节点&&修剪二叉搜索树
开发语言·数据结构·c++·笔记·学习·算法
JustCouvrir1 小时前
代码随想录算法训练营Day15
算法
小小工匠1 小时前
加密与安全_HOTP一次性密码生成算法
算法·安全·htop·一次性密码
中文英文-我选中文1 小时前
排序算法的理解
算法·排序算法
我明天再来学Web渗透2 小时前
【hot100-java】【二叉树的层序遍历】
java·开发语言·数据库·sql·算法·排序算法
数据分析螺丝钉2 小时前
力扣第240题“搜索二维矩阵 II”
经验分享·python·算法·leetcode·面试
no_play_no_games2 小时前
「3.3」虫洞 Wormholes
数据结构·c++·算法·图论
￴ㅤ￴￴ㅤ9527超级帅2 小时前
LeetCode hot100---数组及矩阵专题(C++语言)
c++·leetcode·矩阵