Tap here to switch tabs
Problem
Submissions

Problem: Boundary of Binary Tree

med
30 min
Try to solve the Boundary of Binary Tree problem.

Statement

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

The boundary is formed by concatenating the following four parts:

11. The root node itself (the root is never considered a leaf in this problem).

22. The left boundary: the path of non-leaf nodes starting from the root’s left child, always preferring the left child at each step, and falling back to the right child only when no left child exists. If the root has no left child, the left boundary is empty.

33. The leaves: all nodes with no children, ordered from left to right. The root is excluded even if it has no children.

44. The right boundary (in reverse order): the path of non-leaf nodes starting from the root’s right child, always preferring the right child at each step, and falling back to the left child only when no right child exists, collected in reverse (bottom to top). If the root has no right child, the right boundary is empty.

Note: A leaf node is any node with no left or right child. The root is never treated as a leaf for this problem. The leftmost and rightmost leaves are not included in the left or right boundaries respectively, only in the leaves section.

Constraints:

  • 11 \leq number of nodes 104\leq 10^4

  • 1000-1000 \leq Node.val 1000\leq 1000

Tap here to switch tabs
Problem
Submissions

Problem: Boundary of Binary Tree

med
30 min
Try to solve the Boundary of Binary Tree problem.

Statement

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

The boundary is formed by concatenating the following four parts:

11. The root node itself (the root is never considered a leaf in this problem).

22. The left boundary: the path of non-leaf nodes starting from the root’s left child, always preferring the left child at each step, and falling back to the right child only when no left child exists. If the root has no left child, the left boundary is empty.

33. The leaves: all nodes with no children, ordered from left to right. The root is excluded even if it has no children.

44. The right boundary (in reverse order): the path of non-leaf nodes starting from the root’s right child, always preferring the right child at each step, and falling back to the left child only when no right child exists, collected in reverse (bottom to top). If the root has no right child, the right boundary is empty.

Note: A leaf node is any node with no left or right child. The root is never treated as a leaf for this problem. The leftmost and rightmost leaves are not included in the left or right boundaries respectively, only in the leaves section.

Constraints:

  • 11 \leq number of nodes 104\leq 10^4

  • 1000-1000 \leq Node.val 1000\leq 1000