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;
}
相关推荐
程序员老舅1 小时前
干货|腾讯 Linux C/C++ 后端开发岗面试
linux·c语言·c++·编程·大厂面试题
乐迪信息1 小时前
乐迪信息:基于AI算法的煤矿作业人员安全规范智能监测与预警系统
大数据·人工智能·算法·安全·视觉检测·推荐算法
hsjkdhs2 小时前
C++之多层继承、多源继承、菱形继承
开发语言·c++·算法
立志成为大牛的小牛2 小时前
数据结构——十七、线索二叉树找前驱与后继(王道408)
数据结构·笔记·学习·程序人生·考研·算法
星空下的曙光2 小时前
Node.js crypto模块所有 API 详解 + 常用 API + 使用场景
算法·node.js·哈希算法
Algo-hx2 小时前
数据结构入门 (七):从“链接”到“分支” —— 初探树与二叉树
数据结构
小贾要学习3 小时前
【数据结构】C++实现红黑树
数据结构·c++
StarPrayers.4 小时前
旅行商问题(TSP)(2)(heuristics.py)(TSP 的两种贪心启发式算法实现)
前端·人工智能·python·算法·pycharm·启发式算法
qiuiuiu4134 小时前
正点原子RK3568学习日志-编译第一个驱动程序helloworld
linux·c语言·开发语言·单片机
爱吃橘的橘猫4 小时前
嵌入式系统与嵌入式 C 语言(2)
c语言·算法·嵌入式