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

144. 二叉树的前序遍历

144. 二叉树的前序遍历

在这里插入图片描述

提示:

  1. 树中节点数目在范围 [0, 100] 内

函数原型:

int* preorderTraversal(struct TreeNode* root, int* returnSize) {

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

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

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

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

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

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

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函数构建数组,返回数组。

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

代码

/**
 * 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;
}
  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值