运行环境:VS2019(C语言编写)
问题:写入访问权限冲突(res[*resSize++] = root->val;语句引发)
/****
二叉树前序遍历实现
***/
#include<stdio.h>
#include<malloc.h>
typedef struct TreeNode {
struct TreeNode* left;
struct TreeNode* right;
int val;
}BiTree;
/**
初始化树
***/
void CreateTree(TreeNode **T){
int value = -1;
printf("输入结点的值:\n");
scanf_s("%d", &value);
if (value == -1) {
*T = NULL;
}
else {
*T =(TreeNode*)malloc(sizeof(TreeNode));
(*T)->val = value;
CreateTree(&(*T)->left);
CreateTree(&(*T)->right);
}
}
void PreOrder(struct TreeNode* root,int *res,int *resSize){
if (root == NULL) return;
/***
这里显示写入异常
***/
res[*resSize++] = root->val;
PreOrder(root->left,res,resSize);
PreOrder(root->right,res,resSize);
}
int* PreOrderTraversal(struct TreeNode* root,int *returnSize){
int* res = (int*)malloc(sizeof(int)*2000);
*returnSize = 0;
PreOrder(root,res,returnSize);
return res;
}
int main() {
TreeNode* T;
CreateTree(&T);
int returnSize;
int *head = PreOrderTraversal(T,&returnSize);
//在树的结点值不为0的时候遍历的方式
return 0;
}