EasyStackTreeDepth-First SearchBinary Tree

2 approaches, code in every language

Problem description

You are given the root of a binary tree. Return the values of its nodes visited in inorder sequence.

An inorder traversal processes each subtree in the order left child, then the node itself, then right child. Applied recursively from the root, this rule produces a single flat list of every value in the tree.

For a binary search tree, this ordering happens to yield the values sorted ascending, but the traversal itself is defined purely by the left-node-right visiting rule and works for any binary tree.

Example 1

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

Output: [1,3,2]

The root 1 has no left child, so 1 is emitted first. Its right child 2 has left child 3, so we descend, emit 3, then 2.

Example 2

Input: root = [1,2,3,4,5]

Output: [4,2,5,1,3]

Node 1 has left subtree rooted at 2 (children 4 and 5) and right child 3. Inorder of the left subtree is 4,2,5, then the root 1, then 3.

Constraints

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

After the pattern

Now solve one you haven't seen.

Manifold Valve Readout is our own problem on the technique behind Binary Tree Inorder Traversal: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free