Leetcode144. 二叉树的前序遍历-C语言

文章目录

题目介绍


题目分析

题目要求我们输出二叉树按前序遍历排列的每个节点的值。

解题思路

1.创建一个数组来储存二叉树节点的值

2.根据二叉树的大小来开辟数组的大小

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

 int*new=(int*)malloc(sizeof(int)*Treesize(root));

3.边前序遍历边向创建的数组中存入二叉树节点的值

c 复制代码
void preorder(struct TreeNode* root,int*new,int*newsize)
{
    if(root==NULL)
    return;
    new[(*newsize)++]=root->val;
    preorder(root->left,new,newsize);
    preorder(root->right,new,newsize);
}

完整代码

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

void preorder(struct TreeNode* root,int*new,int*newsize)
{
    if(root==NULL)
    return;
    new[(*newsize)++]=root->val;
    preorder(root->left,new,newsize);
    preorder(root->right,new,newsize);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
    int*new=(int*)malloc(sizeof(int)*Treesize(root));
   *returnSize=0;
 preorder(root,new,returnSize);
 return new;
}
相关推荐
Navigator_Z7 分钟前
LeetCode //C - 1304. Find N Unique Integers Sum up to Zero
c语言·算法·leetcode
晓蛋19 分钟前
C语言第1章概述.ppt
c语言·程序设计·概述·关键字·编译环境
BK贝壳9 小时前
bool-hybrid-array 落盘我只认 .bha:用 Create_BHA / Ask_BHA 做布尔数组序列化
数据结构·python·numpy·1024程序员节
学逆向的9 小时前
C 枚举变量
c语言·开发语言·网络安全
冷凝雨9 小时前
前导零、后导零、最高有效位、最低有效位计算(C)
c语言
鸥梨菌Honevid10 小时前
C 语言 restrict 关键字深度解析:从“独占访问”承诺到编译器激进优化
c语言
企业数字化笔记11 小时前
视频人体姿态怎么做三维可视化?2D关键点、深度局限与技术选型
人工智能·算法·音视频
?abc!12 小时前
(数组)581. 最短无序连续子数组
数据结构·算法·leetcode
小郎君65815 小时前
MPTT树复选框的半选状态:一棵百万节点树从递归到计数器,再到区间覆盖
算法