Anticlockwise Perimeter Walk of an Index-Based Binary Tree
Trees & GraphsAuto-graded · 20 test casesLast updated
Compute the anticlockwise perimeter of a binary tree given as child-index arrays, combining root, left edge, leaves and right edge without duplicates.
You are given a binary tree stored in three parallel arrays. Produce the values on its outer perimeter, listed in anticlockwise order starting at the root.
Input format
- The tree has
nnodes labelled0ton - 1, and node0is the root. values[i]is the value stored in nodei.left[i]andright[i]are the labels of nodei's left and right children, or-1if that child does not exist.
Definitions
- A leaf is a node with no children. The root is never counted as a leaf, even if it has no children.
- The left edge is built as follows. Start at the root's left child. Repeatedly step to the current node's left child if it exists, otherwise to its right child, until you arrive at a leaf. The left edge consists of all nodes visited except that final leaf. If the root has no left child, the left edge is empty.
- The right edge is the mirror image. Start at the root's right child. Repeatedly step to the current node's right child if it exists, otherwise to its left child, until you arrive at a leaf. The right edge consists of all nodes visited except that final leaf. If the root has no right child, the right edge is empty.
- The leaf sequence contains every leaf of the tree, in the order a left-to-right depth-first traversal encounters them.
Task
Return a list of values made by concatenating, in this order:
- the root's value,
- the left edge's values, from top to bottom,
- the leaf sequence's values,
- the right edge's values, from bottom to top.
Every node appears at most once in the result.
Constraints
1 <= n <= 10^4, andlen(values) == len(left) == len(right) == n-1000 <= values[i] <= 1000- Every child index is
-1or between1andn - 1; every node other than0is the child of exactly one node; the links form a single binary tree rooted at node0. - The tree may be a single path, so its depth can be as large as
n.
Examples
Example 1
Input: perimeter_values([1, 2, 3, 4], [-1, 2, -1, -1], [1, 3, -1, -1])
Output: [1, 3, 4, 2]
Example 2
Input: perimeter_values([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 3, 5, -1, 6, 8, -1, -1, -1, -1], [2, 4, -1, -1, 7, 9, -1, -1, -1, -1])
Output: [1, 2, 4, 7, 8, 9, 10, 6, 3]
Example 3
Input: perimeter_values([5], [-1], [-1])
Output: [5]
Hints
Hint 1
Split the answer into four independent pieces: the root, the left edge, the leaves, and the right edge. Decide for each piece exactly which nodes it is allowed to take, so nothing is duplicated.
Hint 2
When walking an edge, prefer the outer child but fall back to the inner child if the outer one is missing. Stop before adding the leaf you land on, since leaves are handled by the leaf pass.
Hint 3
Depth can reach 10^4, so avoid recursion. Use an explicit stack for the leaf pass, pushing the right child before the left so leaves come out left to right, and skip that pass when the root itself has no children.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Build the answer from four separate passes, each with a strict rule about which nodes it may contribute, so no node is listed twice.
- Root. Always first, and listed once. It is never treated as a leaf.
- Left edge. Begin at the root's left child. At each node move to the left child if there is one, otherwise the right child. Add each node's value as you go, but stop on reaching a leaf and do not add it.
- Leaves. Run an iterative preorder traversal with a stack. Push the right child first, then the left, so the left subtree is processed first and leaves appear left to right. Record a node's value only when it is a leaf. Skip this pass if the root is itself childless, otherwise the lone root would be recorded twice.
- Right edge. The mirror of the left edge: prefer the right child, fall back to the left, stop before the leaf. Collect values top to bottom, then reverse them so they are emitted bottom to top.
Concatenate the four parts in that order.
Why it is correct
- Both edge walks start at children of the root, and the leaf pass ignores the root, so the root appears exactly once.
- Both edge walks stop before the leaf they reach, so leaves are only ever output by the leaf pass.
- The left edge lives entirely in the root's left subtree and the right edge entirely in the right subtree. These are disjoint, so the two edges cannot share a node.
- The fallback step matters: a node on the edge that has only an inner child still lies on the outline, so the walk must continue through it rather than stop.
- Preorder with the left child processed first meets leaves in left-to-right order, and reversing the right edge gives the required bottom-to-top order, which together trace the perimeter anticlockwise.
The traversal is iterative because a path-shaped tree of depth 10^4 would overflow Python's default recursion limit.
Complexity
- Time: O(n). Each edge walk touches at most one node per level and the leaf pass visits each node once.
- Space: O(n) for the output and the stack (the stack is O(h), and h can be n).
Reference solution
def perimeter_values(values: list[int], left: list[int], right: list[int]) -> list[int]:
result = [values[0]]
def is_leaf(x):
return left[x] == -1 and right[x] == -1
# Left edge, top to bottom, excluding the final leaf.
node = left[0]
while node != -1 and not is_leaf(node):
result.append(values[node])
node = left[node] if left[node] != -1 else right[node]
# Leaves, left to right, via iterative preorder. The root is never a leaf.
if not is_leaf(0):
stack = [0]
while stack:
node = stack.pop()
if is_leaf(node):
result.append(values[node])
continue
if right[node] != -1:
stack.append(right[node])
if left[node] != -1:
stack.append(left[node])
# Right edge, gathered top to bottom, emitted bottom to top.
right_edge = []
node = right[0]
while node != -1 and not is_leaf(node):
right_edge.append(values[node])
node = right[node] if right[node] != -1 else left[node]
result.extend(reversed(right_edge))
return result