Tree

Term side of the Card.
Topic: Basics
Unit title: Tree
Categories: Data structure
Explanation side of the Card

Explanation: The hierarchical structure where every node except the root has exactly one parent and zero or more child nodes. Commonly used for representing nested data relationships.

Example

Wrongjs
function depth(node) {
  return 1 + Math.max(depth(node.left), depth(node.right));
}
Rightjs
function depth(node) {
  if (node === null) return 0;
  return 1 + Math.max(depth(node.left), depth(node.right));
}

Without the base case the function reads left of null and throws a 'TypeError'.

Common mistakes

  • Assuming a binary search tree stays O(log n) when the inserted data is sorted.
  • Recursing into children without a null check.

Key points

  • Recursive traversal returns at a null node before reading its children.
  • Binary search tree cost is stated as O(h), which is O(n) when the tree is unbalanced.
  • Very deep trees use an iterative traversal with an explicit stack to avoid stack overflow.

Interview questions

Tree vs graph: what is the difference?

A tree is a connected graph with no cycles: n nodes and exactly n - 1 edges, with one path between any two nodes. A graph can have cycles and disconnected parts.

What is the height of a tree?

The number of edges on the longest path from the root to a leaf. A balanced binary tree with n nodes has height O(log n).

What are the tree traversal orders?

Depth-first orders are preorder, inorder and postorder. Level order visits nodes level by level, which is breadth-first search.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy