diff --git a/animations/trees/morris/morrisPostOrder.html b/animations/trees/morris/morrisPostOrder.html new file mode 100644 index 0000000..a6d5986 --- /dev/null +++ b/animations/trees/morris/morrisPostOrder.html @@ -0,0 +1,425 @@ + + +
+ +This animation shows how the Morris post-order traversal algorithm works without using a stack or recursion. Click the "Next Step" button to run the animation.
+ +0. void postorderTraversal(TreeNode* root) {
+1. TreeNode* current = root;
+2. TreeNode* rightmost;
+3. while (current != nullptr) {
+4. if (current->left != nullptr) {
+5. rightmost = current->left;
+6. while (rightmost->right != nullptr && rightmost->right != current) {
+7. rightmost = rightmost->right;
+8. }
+9. if (rightmost->right == nullptr) {
+10. rightmost->right = current;
+11. current = current->left;
+12. } else {
+13. rightmost->right = nullptr;
+14. reverseTraverseRightEdge(current->left);
+15. current = current->right;
+16. }
+17. } else {
+18. current = current->right;
+19. }
+20. }
+21. reverseTraverseRightEdge(root); // traverse the final right edge
+22. return;
+23. }
+24.
+25. TreeNode* reverse(TreeNode* head) {
+26. TreeNode* prev = nullptr;
+27. TreeNode* next = nullptr;
+28. while (head != nullptr) {
+29. next = head->right;
+30. head->right = prev;
+31. prev = head;
+32. head = next;
+33. }
+34. return prev;
+35. }
+36.
+37. void reverseTraverseRightEdge(TreeNode* head) {
+38. TreeNode* tail = reverse(head);
+39. TreeNode* current = tail;
+40. while (current != nullptr) {
+41. std::cout << current->val << " ";
+42. current = current->right;
+43. }
+44. reverse(tail); // restore the original tree structure
+45. }
+