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.
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).
/* _____________ 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,Unlock 150+ medium, hard, and extreme challenges to master advanced TypeScript.
Monthly subscription. Cancel anytime.
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:
TreeNode defines the shape of a binary tree node with a val, left child, and right child[T] extends [TreeNode] checks whether the current node is a real tree node (not null), wrapping in a tuple to avoid distributive conditional typesT is null, we return an empty tuple [] as the base caseThis 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.
Track your progress through 100+ hands-on challenges. Free, sign in with GitHub.
Or start solving right away: explore all TypeScript challenges