Back to Snowflake questions
CodingSoftware Engineer

Boundary of Binary Tree

Role: Software Engineer


Given the root of a binary tree, return the values of its boundary in anti-clockwise direction starting from the root.

The boundary includes:

  • The root.

  • The left boundary (excluding leaves).

  • All leaf nodes from left to right.

  • The right boundary in reverse order (excluding leaves).

If the root has no left or right subtree, then the root itself is the boundary.

Examples

Example 1:

Input: root = [1,null,2,3,4]

Output: [1,3,4,2]

Example 2:

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]

Constraints

  • 1 <= Number of nodes <= 10^4
  • -1000 <= Node.val <= 1000