Morris Preorder Traversal

Binary Trees Traversal in Constant Space Hard
  • Fun Fact: The concept of binary tree traversal, including the efficient Morris preorder traversal, is widely used in the software industry for data analysis and database management
  • For example, SQL uses binary trees and traversal algorithms to fetch, insert, delete or update data records
  • The same concept is applied in GUI rendering, file systems, router algorithms, artificial intelligence for decision-making, and in managing hierarchical data in applications
  • The efficiency and speed of the traversal are essential to performance, making algorithms like Morris preorder traversal crucial in handling larger databases or complex data structures

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