c++ - 使用 Morris 算法对二叉树进行中序遍历时出现分段错误
问题描述
问题链接是这样的:Inorder Traversal (GFG) 我参考了 geeksforgeeks 文章,该文章具有相同的代码但具有 void 函数。我对其进行了修改以适应问题。现在我遇到了分段错误,我不知道为什么。GFG 文章:无递归无栈的中序树遍历!
vector<int> inOrder(Node* root) {
// Your code here
vector<int>ans;
Node* current = root;
Node* pre;
if(!root){return ans;}
while(current){
if(!root->left){
ans.push_back(current->data);
current = current->right;
}
else{
pre = current->left;
while(pre->right && (pre->right != current)){pre = pre->right;}
if(!pre->right){
pre->right = current;
current = current->left;
}
else{
pre->right = NULL;
ans.push_back(current->data);
current = current->right;
}
}
}
return ans;
}
解决方案
以下条件是错误的:
if(!root->left){
这将在每次迭代中进行相同的检查。它应该与当前节点相关:
if(!current->left){
推荐阅读
- c# - Outlook 加载项因太慢而被禁用
- spring - Criteria Builder 在 json 字段中查询 LIKE
- php - 使暂停订单状态通知在 Woocommerce 中工作
- angular - 将 angular.json 中的样式更改为动态
- visual-studio-2015 - 请验证远程工具是否正确安装在远程机器上
- android - 需要触屏两次才能调用 onTouchEvent
- angular - 动态添加锚标签
- c# - PerformanceCounter 在某些机器上不返回值
- selenium - 无法点击使用 findElements 方法获取的链接
- php - 在while循环中形成输入,每一个while输出,而不是只输出一个