Skip to the code
cf.
+25 XP

#333 Inorder Walk in Constant Memory

medium

A smart-watch widget must list the values of a binary tree in inorder (left subtree, node, right subtree), but it can't afford a stack or recursion that grows with the tree's height.

Write inorderNoStack(root) that returns the inorder values using only a constant number of extra variables (the returned list doesn't count). You may change pointers temporarily, but the tree must be exactly as it was when you return. An empty tree returns [].

Example 1

Input: root = [4,2,6,1,3]
Output: [1,2,3,4,6]

Left side 1, 2, 3, then 4, then 6.

Example 2

Input: root = [1,null,2,3]
Output: [1,3,2]

1 has no left side; inside 2's subtree, 3 (its left child) comes before 2.

Constraints

  • 0 <= number of nodes <= 10000

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).