使用 Morris 算法对二叉树进行中序遍历时出现分段错误
I am getting segmentation fault while using Morris algorithm for inorder traversal of a binary tree
问题 link 是这样的:Inorder Traversal (GFG)
我参考了 geeksforgeeks 文章,该文章具有相同的代码但功能无效。我修改它以适应这个问题。现在我遇到了分段错误,我不知道为什么。
GFG 文章:Inorder Tree Traversal without recursion and without stack!
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){
这将使每个迭代中的检查相同。它应该与 current 节点相关:
if(!current->left){
问题 link 是这样的:Inorder Traversal (GFG) 我参考了 geeksforgeeks 文章,该文章具有相同的代码但功能无效。我修改它以适应这个问题。现在我遇到了分段错误,我不知道为什么。 GFG 文章:Inorder Tree Traversal without recursion and without stack!
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){
这将使每个迭代中的检查相同。它应该与 current 节点相关:
if(!current->left){