Trees · Binary Tree Fundamentals

Binary Tree Boundary Traversal

Building the outline of a tree from three independently-collected pieces - the left edge (excluding leaves), every leaf left to right, and the right edge (excluding leaves, reversed) - concatenated so each node on the boundary appears exactly once.

  • 6 min read
  • 9 practice questions
  • 1 graded problem
On this page
  1. Description
  2. The approach
  3. Where you'll see it
  4. Which tool for which job?
  5. Common mistakes
  6. Check yourself
  7. Key takeaways
  8. Quick revise
  9. Practice

Description

A tree's boundary is its outline, traced counterclockwise from the root. Go down the left edge, along every leaf from left to right, and back up the right edge. It isn't one traversal order. It's three pieces read in different directions and stitched together, with care that the root and the leaves at the ends of each edge appear exactly once.

We'll go from simple to more technical:

  1. The pattern: the root, the left edge, the leaves, the right edge reversed.
  2. Where outlining a hierarchy shows up.
  3. The bugs: double-counted nodes and a right edge read the wrong way.
  4. The same output from a single DFS with edge flags.

The approach

Collect three pieces separately, then join them. The left edge runs from the root's left child downward. At each step it goes left, or right if there's no left child, and it skips leaves. The leaves come from a separate walk, left to right. The right edge mirrors the left one from the root's right child. It's collected top to bottom, then reversed so the outline comes back up.

8

4

12

2

6

5

7

15

14

8

4

12

2

6

5

7

15

14

PieceReadNodes
Root8
Left edgetop to bottom, no leaves4 (2 is a leaf, so it's left for the leaf pass)
Leavesleft to right2, 5, 7, 14
Right edgebottom to top, no leaves15, 12 (at 15 there's no right child, so the walk falls back to 14, a leaf)

The boundary is 8, 4, 2, 5, 7, 14, 15, 12.

Java

List<Integer> boundaryTraversal(TreeNode root) {
    List<Integer> result = new ArrayList<>();
    if (!isLeaf(root)) result.add(root.val);
    addLeftBoundary(root.left, result);   // top to bottom, skip leaves
    addLeaves(root, result);               // left to right, only leaves
    addRightBoundary(root.right, result);  // collected top to bottom, then reversed to read bottom to top
    return result;
}

void addLeftBoundary(TreeNode node, List<Integer> result) {
    while (node != null) {
        if (!isLeaf(node)) result.add(node.val);
        node = (node.left != null) ? node.left : node.right;  // prefer left, fall back to right
    }
}
// addRightBoundary is the mirror image, preferring right, collecting into a temp list, then reversed

Python

def boundary_traversal(root: TreeNode) -> list[int]:
    result = []
    if not is_leaf(root):
        result.append(root.val)
    add_left_boundary(root.left, result)    # top to bottom, skip leaves
    add_leaves(root, result)                # left to right, only leaves
    add_right_boundary(root.right, result)  # collected top to bottom, then reversed to read bottom to top
    return result


def add_left_boundary(node: TreeNode | None, result: list[int]) -> None:
    while node is not None:
        if not is_leaf(node):
            result.append(node.val)
        node = node.left if node.left is not None else node.right   # prefer left, fall back to right
# add_right_boundary is the mirror image, preferring right, collecting into a temp list, then reversed

Keeping the three pieces separate keeps each one's rules simple: its own direction, and no leaves on the edges.

Where you'll see it

Drawing only the outer outline of a nested layout, such as a tree of UI panels, has the same structure. The pieces of an outline rarely read in one direction, so each needs its own handling. In interviews, this problem mostly tests careful bookkeeping.

Which tool for which job?

You needUse
The boundary, clearest codethree pieces: left edge, leaves, reversed right edge
The boundary in one traversalDFS carrying "on the left edge" / "on the right edge" flags
Only the leaves, left to rightDFS (or an explicit stack), keeping nodes with no children
The nodes visible from one sidethe level view (next module) - not the same thing
Deep treesiterative edges and an explicit stack for leaves

Common mistakes

MistakeWhat happensDo this instead
Adding edge nodes that are leavesa leaf appears twiceedges skip leaves; the leaf pass adds them
Adding the root when it's a leafa single node appears twiceadd the root only if it has children
Appending the right edge top-downthe outline jumps back to the topreverse it before appending
Using the right subtree when the root has no leftright-side nodes appear as "left edge"the left edge starts at root.left only
Edge walks that stop when a child is missingthe edge ends earlyfall back to the other child

Check yourself

Try to answer before opening each one - recalling beats re-reading.

1. Why do the edge walks skip leaves?

Show answer

The leaf pass already adds every leaf. If an edge walk also added the leaf it ends on, that leaf would appear twice, as 2 would above.

2. Why is the right edge reversed before it's appended?

Show answer

The outline goes down the left side, along the bottom and back up the right side. Walking the right edge naturally gives it top to bottom, the opposite of what the outline needs. Reversing it makes the result one continuous loop instead of jumping back to the top.

3. What does a tree with a single node output?

Show answer

Just that node, once. The root is a leaf, so the root step skips it. Both edge walks start from missing children and add nothing. The leaf pass finds the one leaf and adds it.

Key takeaways

  • The boundary is three pieces joined: left edge, leaves, right edge.
  • The edges skip leaves; the leaf pass adds every leaf exactly once.
  • Collect the right edge top to bottom, then reverse it.
  • An edge walk falls back to the other child when the preferred one is missing.
  • Keeping the pieces separate keeps each one's rules simple.

Quick revise

The whole skill on one page, for the night before an interview.

Everything from the lesson and the deep dive on one page. Skim it before practice or an interview, and open the full lesson for anything that doesn't ring a bell.

Pick the tool

You needUse
Clearestthree pieces
One passDFS with edge flags
Leaves onlyDFS keeping childless nodes

Snippets worth knowing by heart

Java

List<Integer> out = new ArrayList<>();
if (!isLeaf(root)) out.add(root.val);
for (TreeNode n = root.left; n != null; n = n.left != null ? n.left : n.right)
    if (!isLeaf(n)) out.add(n.val);                            // left edge, top-down
addLeaves(root, out);                                          // every leaf, left to right
List<Integer> right = new ArrayList<>();
for (TreeNode n = root.right; n != null; n = n.right != null ? n.right : n.left)
    if (!isLeaf(n)) right.add(n.val);
Collections.reverse(right);                                    // right edge, bottom-up
out.addAll(right);

Python

def dfs(node, left_edge, right_edge):
    if node is None:
        return
    leaf = node.left is None and node.right is None
    if left_edge or leaf:
        out.append(node.val)                                   # preorder: left edge and leaves
    dfs(node.left, left_edge, right_edge and node.right is None)
    dfs(node.right, left_edge and node.left is None, right_edge)
    if right_edge and not leaf and not left_edge:
        out.append(node.val)                                   # postorder: right edge bottom-up

The traps

  • Leaves added twice: an edge walk and the leaf pass both add them. Edges skip leaves.
  • A leaf root added twice: a one-node tree prints its root twice. Add the root alone only if it has children.
  • The right edge not reversed: the outline jumps back to the top. Reverse the right edge before appending it.
  • Borrowing the right subtree as a left edge: right-side nodes appear on the left. The left edge starts at root.left only.
  • Edges stopping at a missing child: the edge ends early. Fall back to the other child.

Staff-level points, one line each

  • No left subtree: the left edge is empty - [1, 3, 4, 2].
  • A single node: [1].
  • One DFS with flags matched the three-piece version on 500 trees.
  • Perfect tree of 1,023 nodes: 529 boundary nodes.

Say it in an interview

  • "The boundary is three pieces: left edge down, leaves left to right, right edge up."
  • "Edges skip leaves so every node appears once."
  • "I reverse the right edge, or add it in postorder."
  • "It's O(n) time because the leaves can be anywhere."

Practice

This skill comes with 9 multiple-choice questions that tell you which misconception a wrong answer reveals and 1 graded problem. Your answers are graded and your mastery is tracked, so you'll know when the skill holds up. Running code and saving progress need a free account.

Practice Binary Tree Boundary Traversal free

Boundary Traversal of Binary Tree

HardProCoding problemJava · Python

Given the root of a binary tree, return its boundary traversal - the tree's outline, each node appearing exactly once:

The full statement, the examples and the hidden test suite are part of AI Proof Engineers Pro.

Practice Binary Tree Boundary Traversal free

No card needed. Lessons, practice questions and easy problems are free forever.

Free plan, no card · 7-day Pro trial · Cancel anytime