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.
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.
Get the latest TypeScript tips, tutorials, and updates delivered straight to your inbox.