TheAlgorithms / C-Plus-Plus

Collection of various algorithms in mathematics, machine learning, computer science and physics implemented in C++ for educational purposes.
https://thealgorithms.github.io/C-Plus-Plus
MIT License
30.79k stars 7.29k forks source link

Add Morris Tree Traversal implementation #2892

Open Ritesh1408 opened 3 weeks ago

Ritesh1408 commented 3 weeks ago

Description of Change

Key Changes: Morris traversal function for in-order traversal Edge case handling for empty trees and single-node trees

Testing: Included tests:

Simple binary trees Skewed trees (left and right) Complex trees with varying node configurations

Sample Test Cases Basic Tree with Depth 2:

Input Tree:

1

/ \ 2 3

Expected In-Order Traversal Output: 2 1 3 Complete Tree with Depth 3:

Input Tree:

  1
/   \

2 3 / \ / \ 4 5 6 7

Expected In-Order Traversal Output: 4 2 5 1 6 3 7 Left-Skewed Tree:

Input Tree:

1

/ 2 / 3 / 4

Right-Skewed Tree:

Input Tree:

1 \ 2 \ 3 \ 4 Expected In-Order Traversal Output: 1 2 3 4 Tree with Only Leaf Nodes on Left Subtree:

Input Tree:

  1
/   \

2 3 / 4 Expected In-Order Traversal Output: 4 2 1 3 Tree with Multiple Levels and Mixed Branching:

Input Tree:

     1
   /   \
  2     3
 / \     \
4   5     6
     \
      7

Expected In-Order Traversal Output: 4 2 5 7 1 3 6

Validation Steps

Memory Efficiency Check: Ensure that the Morris traversal function is not allocating additional memory (stacks or recursion frames) and maintains constant space usage, as it modifies the tree structure for in-order traversal.

Edge Case Handling:

Empty Tree: Input -1 as the first data point to create an empty tree and confirm that Morris traversal handles it gracefully.

Single Node Tree: Input only one node, ensuring the traversal output is the value of that single node.

Output Verification: Compare the Morris traversal output to expected in-order traversal results for each case to confirm accuracy. Notes: Please verify the in-order traversal output matches expected values for different binary tree structures.

Checklist

Notes: