Morris Preorder Traversal

Binary Trees Traversal in Constant Space Hard

Given root of binary tree, return the preorder traversal of the binary tree.


Morris preorder Traversal is a tree traversal algorithm aiming to achieve a space complexity of O(1) without recursion or an external data structure.

Examples:

Input : root = [1, 4, null, 4 2]

Output : [1, 4, 4, 2]

Explanation :

Input : root = [1]

Output : [1]

Explanation : Only root node is present.

Input : root = [1, 4, 2, 9, null, null, 6]

Constraints

  • 1 <= Number of Nodes <= 100
  • -100 Node.val <= 100

Hints

  • If a node has a left child, find its inorder predecessor (rightmost node in the left subtree). Create a temporary link from the inorder predecessor to the current node to allow backtracking. If a node has no left child, visit it directly and move right.
  • Print the node before moving to the left subtree (Preorder: Root → Left → Right). If revisiting via the threaded link, remove the link and move right.

Company Tags

PayPal McKinsey & Company Snowflake Western Digital Zynga Etsy Databricks Ernst & Young Salesforce Morgan Stanley HCL Technologies Lyft Epic Systems Qualcomm Walmart Red Hat Johnson & Johnson Wayfair Robinhood Stripe Roblox Reddit Medtronic KPMG Philips Healthcare Google Microsoft Amazon Meta Apple Netflix Adobe