【C语言题解】 | 144. 二叉树的前序遍历

144. 二叉树的前序遍历

  • [144. 二叉树的前序遍历](#144. 二叉树的前序遍历)
  • 代码

144. 二叉树的前序遍历

提示:

  1. 树中节点数目在范围 [0, 100] 内
c 复制代码

函数原型:

c 复制代码
int* preorderTraversal(struct TreeNode* root, int* returnSize) {

首先先观察一下这个函数原型,TreeNode* root 为形参,传入根节点,int* returnSize为形参,在函数调用时用于返回改题目所求数组的长度,因为由于C语言的局限,只能返回一个参数,所以采用这种通过传入指针的形参,来改变函数外部实参的方法。

题目要求给一个二叉树的根节点,返回其前序遍历的数组。

c 复制代码

首先先计算二叉树的节点个数,用于后续的数组空间申请。

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

然后先序遍历,写入数组:

因为根据上述代码,求得节点个数为n,则该数组一共有n个空间,控制写入数组的下标需要传入int* ,因为若直接传入int,形参的改变不影响实参的改变。

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);
}

使用malloc函数构建数组,返回数组。

c 复制代码
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
    int n = TreeSize(root);
    int* a = (int*)malloc(sizeof(int)*n);
    *returnSize = n;

    int* i = 0;
    preorder(root,a,&i);
    return a;
}

代码

c 复制代码
/**
 * 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().
 */
 int TreeSize(struct TreeNode* root)
 {
     return root == NULL ? 0 : TreeSize(root->left) + TreeSize(root->right) + 1;
 }
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* preorderTraversal(struct TreeNode* root, int* returnSize) {
    int n = TreeSize(root);
    int* a = (int*)malloc(sizeof(int)*n);
    *returnSize = n;

    int* i = 0;
    preorder(root,a,&i);
    return a;
}
相关推荐
xa138508697 分钟前
ARCGIS PRO SDK 多边形四至点计算
算法·arcgis
superman超哥19 分钟前
仓颉语言智能指针深度实战:突破 GC 与所有权的边界
c语言·开发语言·c++·python·仓颉
AuroraWanderll38 分钟前
类和对象(四):默认成员函数详解与运算符重载(下)
c语言·数据结构·c++·算法·stl
2401_8414956438 分钟前
【LeetCode刷题】杨辉三角
数据结构·python·算法·leetcode·杨辉三角·时间复杂度·空间复杂度
Tim_1040 分钟前
【算法专题训练】35、前缀树查找
算法
Cinema KI43 分钟前
二叉搜索树的那些事儿
数据结构·c++
LYFlied1 小时前
【每日算法】LeetCode 62. 不同路径(多维动态规划)
前端·数据结构·算法·leetcode·动态规划
车企求职辅导1 小时前
新能源汽车零部件全品类汇总
人工智能·算法·车载系统·自动驾驶·汽车·智能驾驶·智能座舱
HUST1 小时前
C 语言 第九讲:函数递归
c语言·开发语言·数据结构·算法·c#
yaoh.wang1 小时前
力扣(LeetCode) 119: 杨辉三角 II - 解法思路
数据结构·python·算法·leetcode·面试·职场和发展·跳槽