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;
}
实在是找不到问题出在哪里
TreeNode的定义呢
解决了,是用链表模拟栈的相关代码有问题
修改之后的代码
struct stack {
struct TreeNode* root;
struct stack* next;
};
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
//在栈顶添加元素
void push_back(struct TreeNode* root, struct stack* shead) {
struct stack* cur = shead;
while (cur->next)
cur = cur->next;
struct stack* nextNode = (struct stack*)malloc(sizeof(struct stack));
nextNode->root = root;
nextNode->next = NULL;
cur->next = nextNode;
}
//弹出栈顶元素
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;
}
//获取栈顶元素
struct stack* getTop(struct stack* shead) {
struct stack* cur = shead;
while (cur->next)
cur = cur->next;
return cur;
}
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
int* ret = (int*)malloc(sizeof(int) * 1000);
int retIndex = 0;
struct stack* shead = (struct stack*)malloc(sizeof(struct stack));
shead->next = NULL;
struct stack* cur = shead;
*returnSize = 0;
if (!root) return ret;
push_back(root, shead);
//当栈不为空时
while (shead->next)
{
struct TreeNode* node = getTop(shead)->root;
ret[retIndex++] = node->val;
popTop(shead);
if (node->right) push_back(node->right, shead);
if (node->left) push_back(node->left, shead);
}
*returnSize = retIndex;
return ret;
}