Boundary of Binary Tree

Medium

Topics
TreeDFSBinary Tree

The boundary of a binary tree is the concatenation of the root, the left boundary, the leaves ordered left to right, and the reversed right boundary.

The left boundary is built as follows. The root’s left child is on it; if the root has no left child, the left boundary is empty. From a node on the left boundary, its left child is next, or its right child if it has no left child. Leaves are never on the left boundary.

The right boundary is the mirror image: the root’s right child, then preferring right children over left, and again excluding leaves.

If the root is itself a leaf, the boundary is just the root.

Example 1

11322443
on the boundary, numbered in output order
The boundary is traced anticlockwise from the root: down the left edge, across the leaves left to right, then back up the right edge — which is why the right side comes out reversed. Each node is numbered with its place in the answer, and no node appears twice: the leaves are deliberately excluded from both edges so the leftmost and rightmost ones are reported once, as leaves. The boundary is [1,3,4,2].
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [1,null,2,3,4]
Output: [1,3,4,2]
Explanation: The root has no left child, so the left boundary is empty. The leaves are 3 and 4. The right boundary is just 2, since 4 is a leaf and excluded.

Example 2

43227458511966810739
on the boundary, numbered in output orderinterior, never reported
Input:  root = [1,2,3,4,5,6,null,null,null,7,8,9,10]
Output: [1,2,4,7,8,9,10,6,3]
Explanation: Left boundary 2 (4 is a leaf). Leaves 4, 7, 8, 9, 10. Right boundary 3 then 6, reversed to 6, 3.

Example 3

11
on the boundary, numbered in output order
Input:  root = [1]
Output: [1]
Explanation: The root is a leaf, so it alone forms the boundary.

Constraints

  • 1 <= number of nodes <= 10^4
  • -1000 <= Node.val <= 1000
Editorial — intuition, approach, complexity and pitfalls

Intuition

This is three separate walks glued together, and the only real difficulty is the overlap. A node can belong to more than one of the three categories — the leftmost leaf is both the end of the left boundary and the first leaf — so the rules deliberately exclude leaves from the two boundaries to make each node appear exactly once.

The root is also a special case for the same reason. It would qualify as the start of both boundaries, so it is handled once up front and the two boundary walks start from its children.

And a root with no children is a leaf, which would otherwise be emitted twice: once as the root and once as a leaf. Returning early on that tree removes the clash.

Approach

  1. Emit the root’s value. If the root has no children, stop — that is the whole boundary.
  2. Walk the left boundary from the root’s left child: emit the node, then move to its left child, or its right child if there is no left. Stop on reaching a leaf without emitting it.
  3. Walk the whole tree and emit every leaf in left-to-right order.
  4. Walk the right boundary from the root’s right child by the mirror rule, collecting nodes rather than emitting them, then append them reversed.

Walkthrough

root = [1,2,3,4,5,6,null,null,null,7,8,9,10]

            1
          /   \
         2     3
        / \   /
       4   5 6
          / \ / \
         7  8 9 10

root            -> 1
left boundary   -> 2          (next would be 4, a leaf, so it stops)
leaves          -> 4 7 8 9 10
right boundary  -> 3, 6       (next would be 10, a leaf)
  reversed      -> 6, 3

answer [1,2,4,7,8,9,10,6,3]

Complexity

  • Time — O(n): the two boundary walks are each at most one root-to-leaf path, and the leaf collection visits every node once.
  • Space — O(n): the output, plus recursion depth bounded by the tree height.

Common Pitfalls

  • Not special-casing a root with no children. It gets emitted as the root and again as a leaf, so the answer comes back as two copies of one value.
  • Including leaves in the boundary walks. The leftmost leaf then appears twice, once from the left walk and once from the leaf collection.
  • Taking only left children down the left boundary. The rule falls back to the right child when there is no left one, so a tree that zig-zags still has a left boundary — stopping early truncates it.
  • Forgetting to reverse the right boundary. The boundary is traced anticlockwise, so the right side is read bottom-up.

Full Solution — all languages

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def boundaryOfBinaryTree(self, root):
        def is_leaf(n):
            return n is not None and n.left is None and n.right is None

        if not root:
            return []
        if is_leaf(root):
            return [root.val]

        out = [root.val]

        node = root.left
        while node and not is_leaf(node):
            out.append(node.val)
            node = node.left or node.right

        def leaves(n):
            if not n:
                return
            if is_leaf(n):
                out.append(n.val)
                return
            leaves(n.left)
            leaves(n.right)

        leaves(root)

        right = []
        node = root.right
        while node and not is_leaf(node):
            right.append(node.val)
            node = node.right or node.left

        out.extend(reversed(right))
        return out
SensAI
Beta
Tap the mic to stop voice mode