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;
}
相关推荐
查理零世14 分钟前
【蓝桥杯集训·每日一题2025】 AcWing 6134. 哞叫时间II python
python·算法·蓝桥杯
仟濹14 分钟前
【二分搜索 C/C++】洛谷 P1873 EKO / 砍树
c语言·c++·算法
紫雾凌寒23 分钟前
解锁机器学习核心算法|神经网络:AI 领域的 “超级引擎”
人工智能·python·神经网络·算法·机器学习·卷积神经网络
YH_DevJourney1 小时前
Linux-C/C++《C/8、系统信息与系统资源》
linux·c语言·c++
京东零售技术1 小时前
AI Agent实战:打造京东广告主的超级助手 | 京东零售技术实践
算法
Igallta_8136222 小时前
【小游戏】C++控制台版本俄罗斯轮盘赌
c语言·开发语言·c++·windows·游戏·游戏程序
MiyamiKK572 小时前
leetcode_位运算 190.颠倒二进制位
python·算法·leetcode
C137的本贾尼2 小时前
解决 LeetCode 串联所有单词的子串问题
算法·leetcode·c#
没有不重的名么2 小时前
MATLAB基础学习相关知识
数据结构·学习·matlab
青橘MATLAB学习2 小时前
时间序列预测实战:指数平滑法详解与MATLAB实现
人工智能·算法·机器学习·matlab