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;
}
相关推荐
启观川8 小时前
数据结构与算法 -第 3 章 常用算法-动态规划
数据结构·笔记·python·算法
码爸8 小时前
排序算法介绍
python·算法·排序算法
动词ing9 小时前
【题目练习】算法 组合总和||
算法
wuminyu9 小时前
ForkJoinPool窃取线程在扫描其他WorkQueue时的随机采样算法与Phase线程挂起唤醒机制解析
java·linux·c语言·jvm·c++
longlongzihan9 小时前
链表找环:Floyd 判圈算法(LeetCode 141 & 142 )
c++·算法·leetcode·链表
专业程序开发源9 小时前
flask家电故障预测系统92491-计算机课程设计/毕业设计
vscode·python·sql·算法·flask·课程设计
Logic1019 小时前
C语言/数据结构欧几里得算法题解:长方形切割最大正方形——贪心划分计数
c语言·数据结构·算法·贪心算法·时间复杂度·空间复杂度·欧几里得算法
yi01110 小时前
LeetCode 643. 子数组最大平均数 I|从暴力枚举到滑动窗口
人工智能·笔记·python·算法·leetcode·滑动窗口
极光通讯10 小时前
服务器内存来料检验(IQC)实操:批次追溯、外观判定与上机验证
java·服务器·算法
淡海水10 小时前
02-04-原理篇-GC Roots与对象图遍历
算法·unity·c#·图·gc·遍历·roots