3. Consider the following C++ code snippet implementing Morris inorder traversal on a binary tree with nodes 1, 2, 3 where 1 is root, 2 is left child, and 3 is right child. What is the output printed?
struct Node {
int data;
Node* left;
Node* right;
};
void morrisInorder(Node* root) {
Node* current = root;
while (current != nullptr) {
if (current->left == nullptr) {
std::cout << current->data << " ";
current = current->right;
} else {
Node* pre = current->left;
while (pre->right != nullptr && pre->right != current) {
pre = pre->right;
}
if (pre->right == nullptr) {
pre->right = current;
current = current->left;
} else {
pre->right = nullptr;
std::cout << current->data << " ";
current = current->right;
}
}
}
}
// Tree: 1
// / \
// 2 3
int main() {
Node n1{1, nullptr, nullptr};
Node n2{2, nullptr, nullptr};
Node n3{3, nullptr, nullptr};
n1.left = &n2;
n1.right = &n3;
morrisInorder(&n1);
return 0;
}