A tree organizes nodes through parent-child relationships with one root and no cycles. Depth measures distance from the root, height measures the longest downward path, and a leaf has no children. State whether edge count or node count is used because textbook conventions differ.
General trees organize parent-child relationships. The main question is how nodes relate, not whether values are ordered.
Depth, height, ancestor, descendant, sibling, and leaf are not decorative terms. They describe how algorithms move through the structure.
DFS explores branches deeply before moving across. BFS visits level by level. The traversal choice depends on the problem.
Depth-first traversals use a stack through recursion or an explicit structure: preorder visits before children, postorder after children, and inorder is meaningful for ordered binary trees. Breadth-first traversal uses a queue and processes levels in order.
Every traversal is O(n) when it visits each node once, but auxiliary space depends on shape. A skewed recursive tree can exhaust the call stack; an explicit stack makes the resource visible. Define ownership and cleanup for dynamically allocated nodes.
A general tree node can own a list of children. A binary tree stores at most left and right child links. An array representation is compact for complete binary trees such as heaps, while pointer or index links are more flexible for irregular hierarchies.
| Representation | Strength | Cost |
|---|---|---|
| Child list | Natural for file or category hierarchies | Each node needs a variable-size collection. |
| Left and right links | Direct binary algorithms | Missing children still need null links. |
| Parent array | Compact ancestry queries | Child lookup needs another index or scan. |
| Level-order array | Excellent for complete trees | Sparse shapes waste positions. |
Traversal work is proportional to visited nodes, but height controls recursion depth and many path operations. A balanced binary tree with n nodes has logarithmic height; a one-child chain has linear height.
Do not confuse a tree with a graph that merely looks hierarchical. A valid rooted tree has one path from the root to each node. Import code should detect cycles, missing parents, and nodes with multiple parents when those states violate the model.
Electronics
Computers
Laptops
Monitors
Audio
Headphones
DFS reads down a branch. BFS reads level by level.
Height follows the hierarchy and does not depend on key ordering.
function height(node) {
if (!node) return 0;
return 1 + Math.max(...node.children.map(height), 0);
}
const tree = { value:'root', children:[
{ value:'docs', children:[{ value:'api', children:[] }] },
{ value:'src', children:[] }
]};
console.log(height(tree));
3
No. A BST is a specific ordered binary tree. Many trees are not ordered at all.
Explore 500+ free tutorials across 20+ languages and frameworks.