#3376Medium

InorderTraversal

Implement the type version of binary tree inorder traversal. Master recursive conditional types and tree structures in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement the type version of binary tree inorder traversal, producing a tuple of values by visiting the left subtree, then the current node, then the right subtree.

Challenge Instructions: InorderTraversal

Medium

Implement the type version of binary tree inorder traversal.

For example:

const tree1 = {
val: 1,
left: null,
right: {
val: 2,
left: {
val: 3,
left: null,
right: null,
},
right: null,
},
} as const
 
type A = InorderTraversal<typeof tree1> // [1, 3, 2]

View on GitHub: https://tsch.js.org/3376

Change the following code to make the test cases pass (no type check errors).

ChallengeSolution
/* _____________ Your Code Here _____________ */

interface TreeNode {
  val: number
  left: TreeNode | null
  right: TreeNode | null
}
type InorderTraversal<T extends TreeNode | null> = any

/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '../helpers'

const tree1 = {
  val: 1,
  left: null,
  right: {
    val: 2,
    left: {
      val: 3,
      left: null,
      right: null,
    },
    right: null,
  },
} as const

const tree2 = {
  val: 1,
  left: null,
  right: null,
} as const

const tree3 = {
  val: 1,
  left: {
    val: 2,
    left: null,
    right: null,

Pro Challenge

Unlock 150+ medium, hard, and extreme challenges to master advanced TypeScript.

Monthly subscription. Cancel anytime.

Detailed Explanation

We need a tree node interface and a recursive type that traverses in order: left, root, right.

interface TreeNode {
  val: number
  left: TreeNode | null
  right: TreeNode | null
}
 
type InorderTraversal<T extends TreeNode | null> = [T] extends [TreeNode]
  ? [...InorderTraversal<T['left']>, T['val'], ...InorderTraversal<T['right']>]
  : []

How it works:

This challenge helps you understand recursive conditional types over tree structures and how to apply this concept in real-world scenarios.

This challenge is originally from here.

Share this challenge

Become a TypeScript Pro

Track your progress through 100+ hands-on challenges. Free, sign in with GitHub.

Or start solving right away: explore all TypeScript challenges