Tree Terminology and Traversal
Lesson 29Intermediate52 minAssessment-backed

Tree Terminology and Traversal

Model hierarchical data with roots, children, parents, leaves, depth, height, and traversal order.

What you will be able to do

Explain roots, leaves, height, depth, ancestors, descendants, and subtrees.
Choose DFS or BFS traversal based on the product question.
Implement preorder traversal in Java, Python, and JavaScript.
Connect trees to folders, org charts, DOM trees, menus, and comments.
Avoid cycle assumptions when real data is graph-like.

A tree is a hierarchy: one root, parent-child relationships, and no cycles. That model powers folders, menus, comments, organization charts, DOM nodes, parsers, and many query planners.

Tree Language Engineers Use

A root has no parent. A leaf has no children. Depth counts distance from the root. Height counts the longest path down to a leaf. A subtree is a node plus everything below it. Clear terminology prevents confusion when algorithms recurse.

Tree terminology with root leaves depth and height
Tree vocabulary turns a visual hierarchy into precise engineering language.

Scenario: Product Navigation Menu

A SaaS app has nested navigation: Workspace, Projects, Dashboards, Alerts, Billing. Rendering the menu is a traversal problem. Searching for a visible route may be DFS. Rendering by level or measuring breadth may be BFS.

QuestionTraversalWhy
Render a nested menuDFS/preorderParent appears before children.
Show hierarchy by levelBFS/level orderAll nodes at same depth together.
Compute max depthDFS recursionDepth naturally follows child paths.
Find nearest matching nodeBFSNearest by edges appears first.
DFS and BFS traversal order over a hierarchy
Traversal order should match the product question, not personal preference.

Same Pattern in Java, Python, and JavaScript

Preorder traversal processes the current node before its children. It is natural for rendering, serialization, and command/menu trees.

import java.util.*;

class TreeNode {
    String value;
    List<TreeNode> children = new ArrayList<>();
}

class Preorder {
    static void visit(TreeNode node, List<String> out) {
        if (node == null) return;
        out.add(node.value);
        for (TreeNode child : node.children) visit(child, out);
    }
}

Assessment trap

Real product hierarchies can be corrupted or graph-like. If references may cycle, add visited tracking instead of assuming a perfect tree.

Interview signalFrequently Asked Interview Questions

These are canonical interview patterns for this topic, phrased as concrete problem statements. They avoid vague theory questions and prepare you for the exact reasoning interviewers expect: invariant, edge cases, complexity, and trade-off.

  • Return the values of an n-ary tree level by level.
  • Return the maximum depth of an n-ary tree.
  • Serialize a nested menu tree so it can be stored and rebuilt later.

Production practiceCompany-Style Practice Examples

These are not claimed as exact company-specific questions. They are the interview patterns repeatedly used by product companies to test whether you can move from brute force to a defensible implementation.

ExampleBrute-force approachStronger solutionProduction notes
Org chart renderingFlatten randomly and lose reporting structure.Traverse from root using DFS or BFS based on display requirement.Add cycle protection if imported HR data can be corrupt.
Comment thread moderationScan all comments for each parent.Build children-by-parent once, then traverse from roots.Separates indexing cost from traversal cost.
Navigation sitemapUse BFS for a nested menu that must render parents before descendants.Use preorder DFS so each parent appears before its subtree.Traversal order is a product contract.

Solved modelInterview Question Solutions

Question 1: N-ary Tree Level Order Traversal

Return the values of an n-ary tree level by level. This is BFS. A queue preserves discovery order so each level is processed before the next level.

import java.util.*;

class Node { String val; List<Node> children = new ArrayList<>(); }

class LevelOrderNary {
    static List<List<String>> levelOrder(Node root) {
        List<List<String>> result = new ArrayList<>();
        if (root == null) return result;
        Queue<Node> queue = new ArrayDeque<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<String> level = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                Node node = queue.poll();
                level.add(node.val);
                for (Node child : node.children) queue.offer(child);
            }
            result.add(level);
        }
        return result;
    }
}

Question 2: Maximum Depth of an N-ary Tree

Return the maximum depth of an n-ary tree. Use DFS recursion. A leaf has depth 1; a non-leaf is one plus the largest child depth.

import java.util.*;
class Node { List<Node> children = new ArrayList<>(); }
class NaryDepth { static int maxDepth(Node root) { if (root == null) return 0; int best = 0; for (Node child : root.children) best = Math.max(best, maxDepth(child)); return 1 + best; } }

Question 3: Serialize a Menu Tree

Serialize a nested menu tree so it can be stored and rebuilt later. Preorder works because each parent is emitted before children. Include child counts so decoding knows where each subtree ends.

import java.util.*;
class MenuNode { String id; List<MenuNode> children = new ArrayList<>(); }
class SerializeMenu { static void serialize(MenuNode node, List<String> out) { if (node == null) return; out.add(node.id + ":" + node.children.size()); for (MenuNode child : node.children) serialize(child, out); } }

Solved modelWorked Interview Answer

Return the level-order traversal of an n-ary tree. Level order is BFS. Use a queue because the next node to process is the oldest discovered node at the current frontier.

import java.util.*;

class Node { String val; List<Node> children = new ArrayList<>(); }

class LevelOrderNary {
    static List<List<String>> levelOrder(Node root) {
        List<List<String>> result = new ArrayList<>();
        if (root == null) return result;
        Queue<Node> queue = new ArrayDeque<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<String> level = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                Node node = queue.poll();
                level.add(node.val);
                for (Node child : node.children) queue.offer(child);
            }
            result.add(level);
        }
        return result;
    }
}

Hands-on drillTry It Yourself

Practice task

Draw a folder tree with depth 3. Label root, leaves, depth, height, and the preorder and BFS traversal order.

Failure patternsCommon Mistakes to Avoid

  • Confusing depth and height.
  • Using DFS when nearest-by-level is required.
  • Assuming product data cannot contain cycles.
  • Forgetting null/empty roots.
  • Ignoring traversal order requirements.

Execution guardrailQuick-Start Checklist

  • Name root and child relation.
  • Choose DFS or BFS from the question.
  • Handle empty tree.
  • State time O(nodes).
  • State recursion stack or queue memory.
  • Mention visited set if data may be graph-like.

Recall drillKnowledge Check

QuestionStrong answer
What is a leaf?A node with no children.
What is preorder?Visit node before children.
When does BFS fit?When level or nearest-by-edge order matters.

VocabularyKey Terms

TermMeaning
RootTop node with no parent.
LeafNode with no children.
DepthDistance from root.
HeightLongest downward distance to a leaf.
TraversalSystematic visit order.

Next practiceFurther Reading

  • Practice n-ary tree preorder and level order.
  • Review recursion and queues before tree traversal.
  • Compare trees and graphs when cycles are possible.