【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;
}
相关推荐
半盏茶香2 分钟前
启幕数据结构算法雅航新章,穿梭C++梦幻领域的探索之旅——堆的应用之堆排、Top-K问题
java·开发语言·数据结构·c++·python·算法·链表
小竹子1425 分钟前
L1-1 天梯赛座位分配
数据结构·c++·算法
董董灿是个攻城狮35 分钟前
Transformer 通关秘籍8:词向量如何表示近义词?
算法
独好紫罗兰1 小时前
洛谷题单2-P5712 【深基3.例4】Apples-python-流程图重构
开发语言·python·算法
uhakadotcom1 小时前
NVIDIA Resiliency Extension(NVRx)简介:提高PyTorch训练的容错性
算法·面试·github
梭七y1 小时前
【力扣hot100题】(020)搜索二维矩阵Ⅱ
算法·leetcode·职场和发展
v维焓2 小时前
C++(思维导图更新)
开发语言·c++·算法
ylfhpy2 小时前
Java面试黄金宝典22
java·开发语言·算法·面试·职场和发展
Phoebe鑫2 小时前
数据结构每日一题day9(顺序表)★★★★★
数据结构·算法
烁3472 小时前
每日一题(小白)动态规划篇2
算法·动态规划