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 天前
为啥说:训练用BF16,推理用FP16
人工智能·算法·机器学习
KaMeidebaby1 天前
卡梅德生物技术快报|蛋白 N 端测序在重组贻贝融合蛋白表征中的应用,解决原核表达序列偏移工艺难题
前端·人工智能·物联网·算法·百度
时间的拾荒人1 天前
C语言字符函数与字符串函数完全指南
c语言·开发语言
Turbo正则1 天前
群论在AI中的应用概述
人工智能·算法·抽象代数
ysa0510301 天前
【并查集】判环
c++·笔记·算法
持力行1 天前
C/C++ 中的 char*:它标识数组吗?为什么能用下标访问?
c语言·c++
Jerry1 天前
KeetCode 44. 开发商购买土地
算法
Jerry1 天前
KeetCode 58. 区间和
算法
Jerry1 天前
LeetCode 209. 长度最小的子数组
算法
彦为君1 天前
算法思维与经典智力题
java·前端·redis·算法