A tree is a linked structure where a node can point to more than one node. One node at the top, the root, has no parent. Every other node has exactly one parent, and a node without children is a leaf. Pick any node, and it’s the root of its own subtree.
You work with trees in JavaScript all the time, even if you don’t call them that. The DOM is a tree of elements. A parsed JSON response with nested arrays of objects is a tree. So are comment threads, folders, navigation menus, and org charts.
Two Shapes You’ll Meet
A binary tree gives each node at most two children, usually called left and right, with null for a missing one. Interview problems about search trees use this shape. In a binary search tree, every value in a node’s left subtree is smaller than the node’s value and every value in its right subtree is larger, so you can find a value by going left or right at each step.
An n-ary tree gives each node an array of children, like an element’s children in the DOM or the replies of a comment. Most web data has this shape. JSON from real APIs often leaves out empty arrays, so a leaf may have no children key at all. Read the children with node.children ?? [] instead of assuming the key is there.