Menu
CoddyTech

Boundary Traversal of Binary Tree

The array root holds a binary tree in level order: the root at index 0, the children of index i at 2i+1 (left) and 2i+2 (right), -1 for an empty spot, and possibly extra -1 entries at the end. A leaf is a node with no children.

Return the boundary anticlockwise from the root:

  1. The root.
  2. The left boundary, top to bottom: from the root's left child, move to the left child if there is one, otherwise to the right child. Stop before a leaf.
  3. Every leaf, from left to right.
  4. The right boundary, bottom to top: the mirror of the left one, from the root's right child.

No node is listed twice, so a one-node tree gives only its root.

Function

boundaryTraversal(root: integer-array) → integer-array
rootinteger-array
the binary tree in level order, with -1 for an empty spot
Returnsinteger-array
the boundary values, anticlockwise from the root

Constraints

  • 1 ≤ root.length ≤ 32767
  • Each root[i] is -1 or a value with 0 ≤ root[i] ≤ 105.
  • root[0] is never -1, so the tree has at least one node.
  • The array may end with extra -1 entries past the last node.
  • Both children of an empty spot are empty too, and the depth is at most 14.
  • Node values are distinct.

Examples

Input
root = [7, 3, 9, 1, 5, 8, -1, -1, -1, 4, 6]
Output
[7, 3, 1, 4, 6, 8, 9]
Explanation
After the root 7, the left boundary is 3: its child 1 is a leaf. The leaves are 1, 4, 6, 8. The right boundary is 9, above the leaf 8.
challenge icon

Follow-up

How would you list the boundary clockwise: the root, the right edge top to bottom, the leaves from right to left, then the left edge bottom to top?

Reset code
def boundaryTraversal(root):
    # Write code here

Test #1

Test #2

Test #3

Argument

root = [7, 3, 9, 1, 5, 8, -1, -1, -1, 4, 6]

Expected Output

[7, 3, 1, 4, 6, 8, 9]