【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;
}
相关推荐
JianminZheng25 分钟前
MTPA算法原理及仿真验证
算法
im_AMBER1 小时前
Leetcode 38
笔记·学习·算法·leetcode
Miraitowa_cheems1 小时前
LeetCode算法日记 - Day 82: 环形子数组的最大和
java·数据结构·算法·leetcode·决策树·线性回归·深度优先
Code_Shark2 小时前
AtCoder Beginner Contest 426 题解
数据结构·c++·算法·数学建模·青少年编程
仰泳的熊猫2 小时前
LeetCode:698. 划分为k个相等的子集
数据结构·c++·算法·leetcode
豐儀麟阁贵2 小时前
4.5数组排序算法
java·开发语言·数据结构·算法·排序算法
Jane-6667772 小时前
C语言——栈与队列
c语言·开发语言
Shinom1ya_2 小时前
算法 day 32
算法
richxu202510013 小时前
C语言<<超全.超重要>>知识点总结
c语言·开发语言
WBluuue4 小时前
数据结构与算法:摩尔投票算法
c++·算法·leetcode