Boundary traversal
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Boundary traversal lists the outer edge of a tree: the left side going down, the bottom row of leaves, and the right side going back up. It is a handy way to practise combining several simple walks into one answer.
Practical use cases
- Web app: Outline of a shape in a drawing tool. A web-based drawing tool stores a shape as a tree of points and needs to draw its outline only. Walking the left edge, then the leaves, then the right edge gives the outline points in order. The tool paints the border without touching inner points.
- Web app: Edge nodes in an org chart export. A PDF export of a huge company chart must print a summary page of the outermost people: top leader, far-left chain, all frontline staff, far-right chain. One boundary walk produces that list in reading order, so the summary page builds in a moment.
- System: Tree visualisers and graphics. Tools that draw tree diagrams need the outline to compute margins and avoid overlap. Computer graphics code also traces the border of a region before filling it in. Both only need the edge, so they skip every point inside.
The story: The Boundary Rope Walk
On Sunday the mohalla cricket ground was marked with a long rope. Zoya, the umpire, was told to check the whole rope before the match: "Walk the entire boundary once and tell me if anything is lying on it."
Mira drew the ground as a tree on paper. The root was the pitch end at the top. Zoya's walk had three parts. First she walked down the left side. Then she walked along the bottom, touching every corner where the tree has no more branches (the leaves). Finally she walked back up the right side.
The twist: the right side is naturally met going down, but Zoya had to write it going up. So she collected those names on a small stack and read them back in reverse. And she was careful: a node on the left or right edge that is also a leaf must be written only once. That anticlockwise walk is called the boundary traversal.
How to spot this problem, and where you need it
You need only the outer shell of a tree, not the inner nodes, listed in one continuous order around the edge.
Signs you need it
- The problem says "boundary", "outline", "perimeter", or "anticlockwise order of the edge nodes".
- You must include leaves from the bottom, even when they are in the middle of the tree.
- You are manually joining a left list, a leaf list and a right list, and keep duplicating the corner nodes.
Where to use it in a project
- Drawing outlines or borders for shapes and region maps stored as trees.
- Summary pages and exports that list only the outer people, items or regions.
The solution
Split the job into three. First add the root. Then follow the left edge downward, taking each node that is not a leaf. Then collect every leaf from left to right. Finally follow the right edge, collect nodes that are not leaves, and add them in reverse order so you travel back up. Skip leaves in the edges to avoid duplicates.
Payoff: Before: scanning all 500 nodes to decide which are on the edge. After: three small walks that touch only the edge and the leaves, with no duplicates.
Explain it like I am 8
Draw a tree on paper and trace its outside edge with your finger, anticlockwise, without ever going inside. Every dot you touch goes in the list. Dots hidden in the middle do not make it.
How it works, step by step
- Write down the root (if it is not a leaf; otherwise the leaves step will write it).
- Left boundary: go down from the root's left child. Take the left child if there is one, else the right child. Write every node that is not a leaf.
- Leaves: collect every leaf from left to right with a normal depth-first walk.
- Right boundary: go down the right side the same way (right child first, else left), keep the non-leaf nodes on a stack, then pop them so they come out bottom to top.
The code in four languages
PHP
<?php
class Node {
public ?Node $left = null;
public ?Node $right = null;
public function __construct(public int $val) {}
}
function insert(?Node $n, int $v): Node {
if ($n === null) return new Node($v);
if ($v < $n->val) $n->left = insert($n->left, $v);
else $n->right = insert($n->right, $v);
return $n;
}
function isLeaf(Node $n): bool { return $n->left === null && $n->right === null; }
function addLeaves(?Node $n, array &$out): void {
if ($n === null) return;
if (isLeaf($n)) { $out[] = $n->val; return; }
addLeaves($n->left, $out);
addLeaves($n->right, $out);
}
function boundary(?Node $root): array {
if ($root === null) return [];
$out = isLeaf($root) ? [] : [$root->val]; // 1. the root
$n = $root->left; // 2. left edge, going down
while ($n !== null) {
if (!isLeaf($n)) $out[] = $n->val;
$n = $n->left ?? $n->right;
}
addLeaves($root, $out); // 3. all leaves, left to right
$stack = []; // 4. right edge, written bottom to top
$n = $root->right;
while ($n !== null) {
if (!isLeaf($n)) $stack[] = $n->val;
$n = $n->right ?? $n->left;
}
while ($stack) $out[] = array_pop($stack);
return $out;
}
$root = null;
foreach ([8, 3, 10, 1, 6, 14, 4, 7, 13] as $v) $root = insert($root, $v);
echo implode(' ', boundary($root)), PHP_EOL; // 8 3 1 4 7 13 14 10JavaScript
class Node {
constructor(val) { this.val = val; this.left = null; this.right = null; }
}
function insert(n, v) {
if (n === null) return new Node(v);
if (v < n.val) n.left = insert(n.left, v);
else n.right = insert(n.right, v);
return n;
}
const isLeaf = n => n.left === null && n.right === null;
function addLeaves(n, out) {
if (n === null) return;
if (isLeaf(n)) { out.push(n.val); return; }
addLeaves(n.left, out);
addLeaves(n.right, out);
}
function boundary(root) {
if (root === null) return [];
const out = isLeaf(root) ? [] : [root.val]; // 1. the root
let n = root.left; // 2. left edge, going down
while (n !== null) {
if (!isLeaf(n)) out.push(n.val);
n = n.left ?? n.right;
}
addLeaves(root, out); // 3. all leaves, left to right
const stack = []; // 4. right edge, written bottom to top
n = root.right;
while (n !== null) {
if (!isLeaf(n)) stack.push(n.val);
n = n.right ?? n.left;
}
while (stack.length) out.push(stack.pop());
return out;
}
let root = null;
for (const v of [8, 3, 10, 1, 6, 14, 4, 7, 13]) root = insert(root, v);
console.log(boundary(root).join(' ')); // 8 3 1 4 7 13 14 10Java
import java.util.*;
import java.util.stream.*;
public class Main {
static class Node {
int val;
Node left, right;
Node(int val) { this.val = val; }
}
static Node insert(Node n, int v) {
if (n == null) return new Node(v);
if (v < n.val) n.left = insert(n.left, v);
else n.right = insert(n.right, v);
return n;
}
static Node buildDemo() {
Node root = null;
for (int v : new int[]{8, 3, 10, 1, 6, 14, 4, 7, 13}) root = insert(root, v);
return root;
}
static String join(List<Integer> xs) {
return xs.stream().map(String::valueOf).collect(Collectors.joining(" "));
}
static boolean isLeaf(Node n) { return n.left == null && n.right == null; }
static void addLeaves(Node n, List<Integer> out) {
if (n == null) return;
if (isLeaf(n)) { out.add(n.val); return; }
addLeaves(n.left, out);
addLeaves(n.right, out);
}
static List<Integer> boundary(Node root) {
List<Integer> out = new ArrayList<>();
if (root == null) return out;
if (!isLeaf(root)) out.add(root.val); // 1. the root
Node n = root.left; // 2. left edge, going down
while (n != null) {
if (!isLeaf(n)) out.add(n.val);
n = n.left != null ? n.left : n.right;
}
addLeaves(root, out); // 3. all leaves, left to right
Deque<Integer> stack = new ArrayDeque<>(); // 4. right edge, written bottom to top
n = root.right;
while (n != null) {
if (!isLeaf(n)) stack.push(n.val);
n = n.right != null ? n.right : n.left;
}
while (!stack.isEmpty()) out.add(stack.pop());
return out;
}
public static void main(String[] args) {
System.out.println(join(boundary(buildDemo()))); // 8 3 1 4 7 13 14 10
}
}Go
package main
import (
"fmt"
"strconv"
"strings"
)
type Node struct {
val int
left, right *Node
}
func insert(n *Node, v int) *Node {
if n == nil {
return &Node{val: v}
}
if v < n.val {
n.left = insert(n.left, v)
} else {
n.right = insert(n.right, v)
}
return n
}
func buildDemo() *Node {
var root *Node
for _, v := range []int{8, 3, 10, 1, 6, 14, 4, 7, 13} {
root = insert(root, v)
}
return root
}
func isLeaf(n *Node) bool { return n.left == nil && n.right == nil }
func addLeaves(n *Node, out *[]int) {
if n == nil {
return
}
if isLeaf(n) {
*out = append(*out, n.val)
return
}
addLeaves(n.left, out)
addLeaves(n.right, out)
}
func boundary(root *Node) []int {
out := []int{}
if root == nil {
return out
}
if !isLeaf(root) {
out = append(out, root.val) // 1. the root
}
n := root.left // 2. left edge, going down
for n != nil {
if !isLeaf(n) {
out = append(out, n.val)
}
if n.left != nil {
n = n.left
} else {
n = n.right
}
}
addLeaves(root, &out) // 3. all leaves, left to right
stack := []int{} // 4. right edge, written bottom to top
n = root.right
for n != nil {
if !isLeaf(n) {
stack = append(stack, n.val)
}
if n.right != nil {
n = n.right
} else {
n = n.left
}
}
for len(stack) > 0 {
out = append(out, stack[len(stack)-1])
stack = stack[:len(stack)-1]
}
return out
}
// joinInts glues the numbers together with a separator.
func joinInts(xs []int, sep string) string {
parts := make([]string, len(xs))
for i, v := range xs {
parts[i] = strconv.Itoa(v)
}
return strings.Join(parts, sep)
}
func main() {
fmt.Println(joinInts(boundary(buildDemo()), " ")) // 8 3 1 4 7 13 14 10
}Time: O(n) · Extra space: O(h). Each node is touched a constant number of times; the extra memory is the stack and the recursion, as tall as the tree.
Watch out for
- Writing a corner leaf twice: once in the left edge and again in the leaves step. Skip leaves in the edge steps.
- Forgetting that when a node on the edge has no left child, the edge continues through its right child (and the other way round on the right side).
- Writing the right edge top to bottom. It must come out bottom to top.
Quick check
- In which order do the four parts come?
- Right edge, leaves, left edge
- Root, left edge, leaves, right edge (bottom-up)
- Leaves, root, edges
- Is node 6 (an inside node) part of the boundary in our tree?
- Yes, it is on the left side
- Yes, it is a parent of leaves
- No, it is neither on an edge nor a leaf
- Why is a stack used for the right edge?
- To sort it
- To print it in reverse, bottom to top
- To find leaves