Counterclockwise Perimeter of a Binary Tree
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Given an n-node binary tree encoded with parallel index arrays, implement tree_boundary(values: list[int], left: list[int], right: list[int]) -> list[int] to return the node values along the tree's outer perimeter in counterclockwise (anticlockwise) order starting from the root. (Summing the returned list gives the tree's perimeter total.)
Nodes are labeled 0 through n - 1, with node 0 serving as the root. For each node i, values[i] stores its integer payload, while left[i] and right[i] store the indices of its left and right children, or -1 when the corresponding child is absent.
Perimeter definitions:
- Leaf node: Any node i != 0 with left[i] == -1 and right[i] == -1. Node 0 (the root) is never classified as a leaf, even in a 1-node tree.
- Left boundary: Starts at left[0]. If left[0] == -1, the left boundary is empty ([]). Otherwise, repeatedly advance from the current node u to left[u] if left[u] != -1, or to right[u] if left[u] == -1, halting as soon as you reach a leaf. The left boundary consists of the visited nodes in top-to-bottom order, excluding the terminating leaf.
- Leaves: Every non-root leaf across the tree, ordered from left to right (the order a left-to-right depth-first search visits them).
- Right boundary: Starts at right[0]. If right[0] == -1, the right boundary is empty ([]). Otherwise, repeatedly advance from u to right[u] if right[u] != -1, or to left[u] if right[u] == -1, halting at the first leaf and excluding that leaf. In the final perimeter list, right-boundary values are ordered from bottom to top.
Concatenate and return:
1. The root value (values[0]),
2. Left-boundary values from top to bottom,
3. Leaf values from left to right,
4. Right-boundary values from bottom to top.
Examples
Example 1
10
\
20
/ \
30 40
/
50
Input:
values = [10, 20, 30, 40, 50]
left = [-1, 2, -1, 4, -1]
right = [ 1, 3, -1, -1, -1]
Output:
[10, 30, 50, 40, 20]
Explanation: Because left[0] == -1, the left boundary is empty. Left-to-right leaves are 30 and 50. Walking down from right[0] = 1 visits 20, then 40, and turns inward to 50 (a leaf, where it stops); reversing [20, 40] yields [40, 20]. The perimeter sum is 150.
Example 2
10
/ \
5 18
\ / \
7 14 25
/ \ /
2 6 12
Input:
values = [10, 5, 18, 7, 14, 25, 2, 6, 12]
left = [ 1, -1, 4, 6, 8, -1, -1, -1, -1]
right = [ 2, 3, 5, 7, -1, -1, -1, -1, -1]
Output:
[10, 5, 7, 2, 6, 12, 25, 18]
Explanation: Root is 10. The left boundary starts at 5, falls back to its right child 7, and stops before leaf 2, giving [5, 7]. Left-to-right leaves are [2, 6, 12, 25] (interior node 14 is enclosed inside the tree and excluded). The right boundary starts at 18 and stops before leaf 25, giving [18].
Example 3
Input:
values = [-4]
left = [-1]
right = [-1]
Output:
[-4]
Explanation: Because node 0 is never treated as a leaf, both side boundaries and the leaf list are empty, so -4 is emitted once.
Constraints
1 <= n <= 10^4, withlen(values) == len(left) == len(right) == n-1000 <= values[i] <= 1000- Every element in
leftandrightis either-1or an integer in[1, n - 1]. Every node in1 .. n - 1has exactly one parent, forming a single valid binary tree rooted at node0. - Tree height can be up to
n(for instance, a degenerate chain).
Step-by-step walkthrough
Understand the four parts of the anticlockwise tour
The tree has
nnodes numbered0ton - 1, stored in three parallel arrays:values[i]holds nodei's number, whileleft[i]andright[i]hold the indices of its left and right children (or-1if that child does not exist). Node0is always the root.Walking the outer perimeter anticlockwise starting from the root visits four segments in order: 1. The root (
node 0). 2. The left boundary (top to bottom), starting atleft[0]and stopping before the first leaf. 3. All leaves (left to right), where a leaf has no children (left[i] == -1andright[i] == -1). 4. The right boundary (bottom to top), starting atright[0], stopping before the first leaf, and reversed on the way back up.Here is Example 2 drawn with node values so you can see all four parts at once:
[10] <-- 1. Root: [10] / \ (5) (18) <-- 2. Left boundary (down): [5, 7] \ / \ 4. Right boundary (up): [18] (7) 14 <25> (note: 5 has no left child, so it turns right to 7; / \ / interior node 14 is enclosed and skipped!) <2> <6><12> <-- 3. Leaves (left to right): [2, 6, 12, 25] Anticlockwise output: [10] + [5, 7] + [2, 6, 12, 25] + [18] = [10, 5, 7, 2, 6, 12, 25, 18]Keep three critical rules in mind: - The root is never a leaf, even when
n = 1and the root has no children. - Ifleft[0] == -1, the left boundary is empty (do not cross into the right subtree to look for a left boundary!), and likewise on the right whenright[0] == -1. - A side boundary turns inward when its preferred child is missing (like(5) -> (7)above), and excludes the leaf where it stops so that leaf is not counted twice.Why the four parts never duplicate a node (and why we avoid recursion)
Do we need a
visitedset to prevent printing the same node twice? Let us check the four groups: - Group 1 is{0}(the root alone). - Group 2 contains only non-leaf nodes insideleft[0]'s subtree. - Group 3 contains only non-root leaf nodes across the tree. - Group 4 contains only non-leaf nodes insideright[0]'s subtree.Because left and right subtrees of a tree never share nodes, and leaves never overlap with non-leaves (or with node
0), all four groups are 100% disjoint! We can compute each piece cleanly on its own and concatenate them.One practical trap remains:
ncan be10,000, and the tree can be a single skinny chain of depth10,000. In Python, the default recursion limit is1,000, so a recursive tree walk will crash withRecursionError. Writing each walk as a simplewhileloop handles any depth safely.Walk a side boundary with preferred and fallback children
Notice that the left boundary and the right boundary follow the exact same rule—just with
leftandrightswapped! - Left boundary: start atleft[0], preferleft[node], fall back toright[node]. - Right boundary: start atright[0], preferright[node], fall back toleft[node].Let us trace how one shared helper
collect_side_boundary(start_node, preferred_child, fallback_child)walks the right side of Example 1 (start_node = 1, which has value20):node = 1 (val 20): has children 2,3 -> not a leaf -> append 1; preferred right[1] = 3 node = 3 (val 40): has child left=4 -> not a leaf -> append 3; right[3] is -1, fallback left[3] = 4 node = 4 (val 50): left=-1, right=-1 -> IS A LEAF -> break! (excluded from right boundary) Result (top-down node indices): [1, 3]Here is the helper function:
def collect_side_boundary( start_node: int, preferred_child: list[int], fallback_child: list[int], ) -> list[int]: boundary_nodes: list[int] = [] node = start_node while node != -1: # Stop BEFORE appending a leaf so it is listed only once during `collect_leaves`. is_leaf = preferred_child[node] == -1 and fallback_child[node] == -1 if is_leaf: break boundary_nodes.append(node) # Hug the outer edge if possible; otherwise turn inward to the other child. if preferred_child[node] != -1: node = preferred_child[node] else: node = fallback_child[node] return boundary_nodesCollect leaves left-to-right with an explicit stack
To visit every leaf from left to right without recursion, we run an iterative depth-first search (DFS)—an exploration that plunges all the way down one branch before backing up—using a Python list
stack = [0]as a LIFO stack (Last-In, First-Out:stack.pop()always removes whichever node was appended most recently).Watch the push order carefully! Because the last child pushed is popped first, we must push
right[node]first andleft[node]second so that the entire left subtree is explored before the right subtree:At root 0 (left=1, right=2): pop 0 -> push right (2), then push left (1) -> stack = [2, 1] (top is 1!) Next step: pop 1 -> explores everything under node 1 (left side) BEFORE touching 2 (right side)And whenever we pop a node with no children, we check
node != 0so a single-node root is never added as a leaf:def collect_leaves(left: list[int], right: list[int]) -> list[int]: leaves: list[int] = [] stack: list[int] = [0] while stack: node = stack.pop() has_no_children = left[node] == -1 and right[node] == -1 # Rule: the root (node 0) is never treated as a leaf, even if it has no children. if node != 0 and has_no_children: leaves.append(node) # Push right BEFORE left so left sits on top of the stack and is popped first. if right[node] != -1: stack.append(right[node]) if left[node] != -1: stack.append(left[node]) return leavesAssemble the four segments in anticlockwise order
Now
tree_boundaryputs the four pieces together, converting node indices intovalues[node]. Becausecollect_side_boundary(right[0], right, left)collects the right boundary from top to bottom, iterating overreversed(right_boundary)walks from bottom to top—completing the anticlockwise circle back up to the root (and if you ever need the boundary sum, it is simplysum(result)):def tree_boundary(values: list[int], left: list[int], right: list[int]) -> list[int]: result: list[int] = [values[0]] left_boundary = collect_side_boundary(left[0], left, right) for node in left_boundary: result.append(values[node]) leaf_nodes = collect_leaves(left, right) for node in leaf_nodes: result.append(values[node]) right_boundary = collect_side_boundary(right[0], right, left) for node in reversed(right_boundary): result.append(values[node]) return resultTrace all three examples step by step
Let us verify our helpers on all three examples from the problem statement:
Example 1: values = [10, 20, 30, 40, 50], left = [-1, 2, -1, 4, -1], right = [1, 3, -1, -1, -1] 1. Root: values[0] = 10 2. Left boundary: start = left[0] = -1 -> [] 3. Leaves: nodes 2, 4 -> values [30, 50] 4. Right boundary: start = right[0] = 1 (val 20) -> right[1] = 3 (val 40) -> left[3] = 4 (leaf, stop!) reversed([1, 3]) -> values [40, 20] Output: [10, 30, 50, 40, 20] Example 2: values = [10, 5, 18, 7, 14, 25, 2, 6, 12] 1. Root: [10] 2. Left boundary: nodes [1, 3] (vals 5, 7) -> stops before leaf node 6 (val 2) -> [5, 7] 3. Leaves: nodes 6, 7, 8, 5 -> values [2, 6, 12, 25] 4. Right boundary: node [2] (val 18) -> stops before leaf node 5 (val 25) -> [18] Output: [10, 5, 7, 2, 6, 12, 25, 18] Example 3: values = [-4], left = [-1], right = [-1] 1. Root: [-4] 2. Left boundary: start = -1 -> [] 3. Leaves: node 0 skipped because `node != 0` -> [] 4. Right boundary: start = -1 -> [] Output: [-4]Complete solution
Putting both helpers and
tree_boundarytogether gives the completeO(n)iterative solution:from typing import Any, Dict, List, Optional, Set, Tuple def collect_side_boundary( start_node: int, preferred_child: list[int], fallback_child: list[int], ) -> list[int]: # Phase 1 helper: Walk one outer boundary from `start_node` top-to-bottom, # stopping right before the first leaf. # boundary_nodes: list of non-leaf node indices on this boundary (e.g., [2, 5]). boundary_nodes: list[int] = [] node = start_node while node != -1: # A node is a leaf when both of its children are missing (-1). # Stop BEFORE appending a leaf so it is listed only once during `collect_leaves`. is_leaf = preferred_child[node] == -1 and fallback_child[node] == -1 if is_leaf: break boundary_nodes.append(node) # Hug the outer edge if possible; otherwise turn inward to the other child. if preferred_child[node] != -1: node = preferred_child[node] else: node = fallback_child[node] return boundary_nodes def collect_leaves(left: list[int], right: list[int]) -> list[int]: # Phase 2 helper: Collect all non-root leaf indices from left to right. # Use an explicit stack instead of recursion because a skewed chain of 10^4 nodes # exceeds Python's default recursion limit of 1,000. # leaves: list of leaf node indices in left-to-right order (e.g., [3, 6, 7, 8, 9]). leaves: list[int] = [] # stack: LIFO list of pending node indices to visit, starting at root 0. stack: list[int] = [0] while stack: node = stack.pop() has_no_children = left[node] == -1 and right[node] == -1 # Rule: the root (node 0) is never treated as a leaf, even if it has no children. if node != 0 and has_no_children: leaves.append(node) # Push the right child BEFORE the left child onto the LIFO stack so that # the left child sits on top and the entire left subtree is visited first. if right[node] != -1: stack.append(right[node]) if left[node] != -1: stack.append(left[node]) return leaves def tree_boundary(values: list[int], left: list[int], right: list[int]) -> list[int]: # Phase 3: Concatenate the four disjoint segments of the anticlockwise tour: # 1. Root value (node 0) result: list[int] = [values[0]] # 2. Left boundary values from top to bottom (prefer left child, fall back to right) left_boundary = collect_side_boundary(left[0], left, right) for node in left_boundary: result.append(values[node]) # 3. All leaf values from left to right leaf_nodes = collect_leaves(left, right) for node in leaf_nodes: result.append(values[node]) # 4. Right boundary values from bottom to top: walk top-down preferring right, # then reverse to climb back up toward the root anticlockwise. right_boundary = collect_side_boundary(right[0], right, left) for node in reversed(right_boundary): result.append(values[node]) return result✅ Submit now — all tests should pass.
Intuition & how it works
Picture walking anticlockwise around the outside perimeter of a branching garden starting at the entrance gate at the top (the root): first you record the gate itself, then you walk down the leftmost path (stopping just before the bottom tip), then you stroll across all the dead-end tips (leaves) from left to right, and finally you climb back up the rightmost path from bottom to top without ever stepping on the same stone twice.
Beginners often run into three traps when coding this directly: (1) only stepping to left[node] on the left boundary instead of turning inward to right[node] when a left child is missing; (2) including the bottom leaf node (a node with neither a left child nor a right child) in both the side walk and the leaf walk, or counting a lone childless root as a leaf, which duplicates values; and (3) writing a recursive tree walk, which hits Python's default recursion limit (the maximum number of nested function calls Python allows on the call stack, around 1,000) when the tree is a 10,000-node chain.
Instead, we break the tour into four non-overlapping pieces using simple iterative loops and an explicit LIFO stack (a Last-In, First-Out list where the most recently pushed item is popped next) to perform depth-first search (DFS) (exploring all the way down one branch before backtracking to sibling branches). Let us trace Example 1 (values = [10, 20, 30, 40, 50], left = [-1, 2, -1, 4, -1], right = [1, 3, -1, -1, -1]):
1. Root: Start with [values[0]] = [10].
2. Left boundary: left[0] is -1, so the left boundary is immediately [] (we never cross into right[0] for the left boundary).
3. Leaves (left-to-right DFS): Starting from 0, the stack visits node 1, then its left child 2 (leaf, value 30), and down node 3 to 4 (leaf, value 50), giving [30, 50].
4. Right boundary (bottom-to-top): Starting at right[0] = 1 (value 20), we keep 20, advance to right[1] = 3 (value 40, keep 40), fall back to left[3] = 4, see that node 4 is a leaf, and stop! Reversing [20, 40] gives [40, 20], so the final answer is [10] + [] + [30, 50] + [40, 20] = [10, 30, 50, 40, 20].
Complexity
Let n be the number of nodes in the binary tree.
- Time:
O(n). Each side-boundary loop steps down one tree level per iteration and therefore visits at mostnnodes inO(n)time,collect_leavespushes and pops each of thennodes onstackexactly once inO(n)time, and buildingresultcopies at mostnvalues once. - Space:
O(n). On a skewed chain ofnnodes,stack, a side-boundary list, andresultcan each hold up toO(n)items (andO(height)forstackand the side paths on balanced trees).
Edge cases
- Single-node tree (
n = 1):left[0] == -1andright[0] == -1. Both side boundaries are empty, andnode != 0prevents the root from being treated as a leaf, returning[values[0]]once. - Missing left or right subtree on the root: When
left[0] == -1(as in Example 1),collect_side_boundary(-1, ...)immediately exits thewhileloop and returns[], rather than mistakenly treatingright[0]as part of the left boundary. - Root's direct child is already a leaf: For example,
left[0] = 1where node1has no children.collect_side_boundaryseesis_leaf == Trueon node1right away and returns[], so node1is emitted once duringcollect_leaves. - Zigzag side boundaries: When a node on the left boundary has
left[node] == -1andright[node] != -1(like5 -> 7in Example 2, or40 -> 50on the right boundary in Example 1), falling back to the inner child keeps tracing the true outer silhouette. - Skewed chain of
10^4nodes: Because bothcollect_side_boundaryandcollect_leavesusewhileloops rather than recursion, a10,000-deep chain finishes in milliseconds with zeroRecursionError. - Duplicate or negative node values, and arbitrary node indices: Checking
node != 0by node index (never byvalues[node]) handles duplicate values cleanly, and child links work regardless of whether child indices are larger or smaller than parent indices.
Common mistakes
- Counting a lone root as both the root and a leaf: Omitting
node != 0incollect_leavesoutputs[-4, -4]instead of[-4]on Example 3. - Pushing
left[node]beforeright[node]ontostack: Because a stack is Last-In, First-Out, pushingleftfirst putsrighton top, visiting leaves from right to left instead of left to right! - Appending before checking
is_leafincollect_side_boundary: Adds the bottom-most leaf of a boundary into the side list as well as the leaf list, duplicating up to two leaves in the result. - Forgetting
reversed(right_boundary): Emits the right side from top to bottom instead of climbing bottom to top anticlockwise. - Starting the left boundary at node
0instead ofleft[0]: Whenleft[0] == -1andright[0] != -1, starting at0with fallback torightmakes the "left boundary" walk down the right side of the tree! - Using recursive DFS for
collect_leaves: Hits Python's ~1,000-frame recursion limit on deep chains (n <= 10^4).
Alternative approaches
- Single iterative preorder pass with boundary flags: A preorder traversal visits each node before its left and right subtrees. You can push
(node, on_left_boundary, on_right_boundary)tuples onto one explicit stack: a child inheritson_left_boundaryif it isleft[node](orright[node]whenleft[node] == -1), and symmetrically foron_right_boundary. Non-root leaves go toleaves, flagged non-leaves go toleft_sideorright_side, and at the end you return[values[0]] + left_side + leaves + right_side[::-1]inO(n)time—though keeping three separate small functions is much easier to read and debug in an interview.
Follow-up questions
- How would you modify the algorithm to return the perimeter in clockwise order starting from the root? A clockwise tour visits the root, then the right boundary top-to-bottom, then the leaves right-to-left, and finally the left boundary bottom-to-top. Notice that
[right_top_down] + [leaves_right_to_left] + [left_bottom_up]is the exact reverse of[left_top_down] + [leaves_left_to_right] + [right_bottom_up]! So you can compute the anticlockwise listans = tree_boundary(values, left, right)and return[ans[0]] + ans[1:][::-1]inO(n)time (or simply swap theleftandrightarguments passed intotree_boundary). - If the input arrays come from an untrusted caller, how can you verify in O(n) time that they represent a single valid binary tree rooted at node 0? First check
len(values) == len(left) == len(right) == nwithn >= 1, and verify every non--1entry is an integer in1 .. n - 1(node0cannot have a parent) while counting how many times each node appears as a child. Every node in1 .. n - 1must have parent count1(givingn - 1total edges). Finally, run an iterative stack traversal from0using a booleanseenarray of sizenand confirm allnnodes are reached—a connected directed graph onnnodes withn - 1edges and in-degree1everywhere except root0is guaranteed to be a cycle-free single tree. - What changes if the tree is passed as pointer-based node objects instead of parallel index arrays? The three-walk structure stays identical, replacing
-1checks withnode is None, array lookupsleft[node]/right[node]withnode.left/node.right(or a small helperpreferred(node)/fallback(node)), andnode != 0with object identitynode is not root(nevernode.val != root.val, since other nodes can share the root's value). Keepingcollect_leavesiterative withstack = [root]remains essential so deep pointer-based trees do not overflow the call stack.
Follow-up questions
- How would you modify the algorithm to return the perimeter in clockwise order starting from the root?
- If the input arrays come from an untrusted caller, how can you verify in O(n) time that they represent a single valid binary tree rooted at node 0?
- What changes if the tree is passed as pointer-based node objects instead of parallel index arrays?
Similar questions
- Memoized First-Occurrence Binary Search
- Match Every Person to the Closest Cake Index
- Preorder Org-Chart Listing from Direct-Report Pairs
- Compute Subtree Value Totals Across a Parent-Array Tree
- Contiguous Subarray Match for Recipe in Menu
- Validate a Proposed Course Completion Sequence
More Snowflake interview questions
- Fewest Node Removals to Cap Tree Height Medium
- Thread-Safe Per-Key Token Bucket Rate Limiter Medium
- Log Fault Search and Service Outage Cascades Medium Pro
- Computing Inherited Access Grants Across a Permission DAG Medium Pro
- Minimum Edits to Form a Perfect Binary Tree Medium Pro
- Locate All Valid Sets in a Four-Feature Deck Hard Pro
- Multiway Tree Height Under Node Removal and Promotion Medium Pro
- Resulting N-ary Tree Height When Splicing Out Nodes Medium Pro
- Per-Key Sliding-Window Request Limiter Medium Pro
- Rooted Tree Height After Node Removals Medium Pro