Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Morris Traversal Implementation

HardPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Morris Traversal Implementation. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Josh Technology Group's engineering tools may need to inspect hierarchical data without allocating traversal stacks for large trees. Given the root of a binary tree, return its inorder traversal using Morris traversal, which temporarily creates and removes predecessor links.

Implement morris_inorder(root). The input is a TreeNode object with integer field val and optional left and right child references. Return a list of values visited in inorder: left subtree, current node, right subtree. The traversal must restore every temporary pointer before returning.

For examples and test cases, trees are represented as level-order arrays, where null means no node. The evaluator constructs the corresponding TreeNode graph before calling the function.

Constraints

  • 0 <= n <= 10^5, where n is the number of nodes
  • -10^9 <= node.val <= 10^9
  • The input is a valid binary tree
  • The tree must be restored before the function returns
  • Auxiliary space must be O(1), excluding the output list

Function Signature

def morris_inorder(root):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output