|
| 1 | +#include <iostream> |
| 2 | +using namespace std; |
| 3 | + |
| 4 | +struct TreeNode { |
| 5 | + int val; |
| 6 | + TreeNode* left; |
| 7 | + TreeNode* right; |
| 8 | + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 9 | +}; |
| 10 | + |
| 11 | +void morrisInorderTraversal(TreeNode* root) { |
| 12 | + TreeNode* current = root; |
| 13 | + |
| 14 | + while (current != nullptr) { |
| 15 | + if (current->left == nullptr) { |
| 16 | + // If no left child, visit current and move to the right |
| 17 | + cout << current->val << " "; |
| 18 | + current = current->right; |
| 19 | + } else { |
| 20 | + // Find the in-order predecessor of current |
| 21 | + TreeNode* predecessor = current->left; |
| 22 | + while (predecessor->right != nullptr && predecessor->right != current) { |
| 23 | + predecessor = predecessor->right; |
| 24 | + } |
| 25 | + |
| 26 | + if (predecessor->right == nullptr) { |
| 27 | + // Establish temporary link from predecessor's right to current |
| 28 | + predecessor->right = current; |
| 29 | + current = current->left; |
| 30 | + } else { |
| 31 | + // Remove temporary link and visit current |
| 32 | + predecessor->right = nullptr; |
| 33 | + cout << current->val << " "; |
| 34 | + current = current->right; |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +int main() { |
| 41 | + // Example tree |
| 42 | + TreeNode* root = new TreeNode(1); |
| 43 | + root->left = new TreeNode(2); |
| 44 | + root->right = new TreeNode(3); |
| 45 | + root->left->left = new TreeNode(4); |
| 46 | + root->left->right = new TreeNode(5); |
| 47 | + |
| 48 | + cout << "Morris In-order Traversal: "; |
| 49 | + morrisInorderTraversal(root); // Expected Output: 4 2 5 1 3 |
| 50 | + return 0; |
| 51 | +} |
0 commit comments