Boundary of Binary Tree

Medium · Trees · Tree · Depth-First Search · Binary Tree

Problem

The boundary of a binary tree is, in this order: the root, the left boundary, the leaves from left to right, and the right boundary in reverse (bottom-up). Each node appears once.

Given the root of a binary tree, return the values on its boundary in that order.

Examples

Input: root = [1,2,3,4,5,6,None,None,None,7,8]
Output: [1,2,4,7,8,6,3]

The left boundary is [2]; the leaves are [4, 7, 8, 6]; the right boundary is [3], appended reversed.

Input: root = [1,None,2,3,4]
Output: [1,3,4,2]

There is no left child, so the left boundary is empty. The leaves are [3, 4] and the right boundary is [2].

Input: root = [5]
Output: [5]

A lone root is the whole boundary, listed once.

Constraints

Approaches

Follow-up

The three parts can also be gathered in a single preorder pass that carries two flags, "on the left boundary" and "on the right boundary": add a node before its children when it is on the left boundary or a leaf, and after its children when it is on the right boundary, which produces the reversal for free.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…