TOP101题解 | BM23#二叉树的前序遍历#
二叉树的前序遍历
https://www.nowcoder.com/practice/5e2135f4d2b14eb8a5b06fab4c938635
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* @author Senky
* @date 2023.05.06
* @par url https://www.nowcoder.com/creation/manager/content/584337070?type=column&status=-1
* @param root TreeNode类
* @return int整型一维数组
* @return int* returnSize 返回数组行数
*/
/*要是定义成int* str 会出错,用malloc申请空间又无法确定大小(上限100)
虽然允许定义一个不知道大小的数组,但是不能将其初始化,不过这里仍然会给个警告*/
int str[];
void PreOrderVisit(struct TreeNode* root,int* returnSize)
{
if(root)
{
str[(*returnSize)++] = root->val;
PreOrderVisit(root->left,returnSize);
PreOrderVisit(root->right,returnSize);
}
}
int* preorderTraversal(struct TreeNode* root, int* returnSize ) {
// write code here
*returnSize = 0;
PreOrderVisit(root,&(*returnSize));
return str;
}
很简单的前序遍历递归调用,没什么好说的
#TOP101#TOP101-BM系列 文章被收录于专栏
系列的题解
查看3道真题和解析