问题遇到的现象和发生背景
leetcode144 非递归遍历二叉数
发生member access within misaligned address错误
用代码块功能插入代码,请勿粘贴截图
struct stack {
struct TreeNode* root;
struct stack* next;
};
//在cur后面添加栈元素
void push_back(struct TreeNode* root, struct stack* cur) {
struct stack* nextNode = (struct stack*)malloc(sizeof(struct stack));
nextNode->root = root;
nextNode->next = NULL;
cur->next = nextNode;
cur = cur->next;
}
void popTop(struct stack* shead) {
struct stack* slow = shead;
struct stack* fast = slow->next;
if (!fast) return;
while (fast->next)
{
slow = slow->next;
fast = fast->next;
}
free(fast);
slow->next = NULL;
}
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
int ret[1000];
int retIndex = 0;
struct stack* shead = (struct stack*)malloc(sizeof(struct stack));
shead->next = NULL;
struct stack* cur = shead;
int stackTop = 0;
*returnSize = 0;
if (!root) return ret;
push_back(root, cur);
//当栈不为空时
while (shead->next)
{
struct TreeNode* node = cur->root;
ret[retIndex++] = node->val;
popTop(shead);
if (node->right) push_back(node->right, cur);
if (node->left) push_back(node->left, cur);
}
*returnSize = retIndex;
return ret;
}
运行结果及报错内容
实在是找不到问题出在哪里