Boundary Traversal

Binary Trees FAQs Medium

Given a root of Binary Tree, perform the boundary traversal of the tree. 


The boundary traversal is the process of visiting the boundary nodes of the binary tree in the anticlockwise direction, starting from the root.

Examples:

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

Output : [1, 2, 4, 8, 9, 6, 7, 3]

Explanation :

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

Output : [1, 2, 4, 6, 5, 7, 8]

Explanation :

Input : root = [5, 1, 2, 8, null, 4, 5, null, 6]

Constraints

  • 1 <= Number of Nodes <= 104
  • -103 <= Node.val <= 103

Hints

  • Start from the left child of the root. Move down the left subtree, collecting the first node encountered at each level. Stop when a leaf node is reached (do not include leaves in this step).
  • Start from the right child of the root. Move down the right subtree, collecting the first node encountered at each level. Do not include leaves. Store the values in reverse order before adding them to the final result.

Company Tags

GE Healthcare Visa Red Hat Unity Technologies Bloomberg Nutanix Byju's OYO Rooms Siemens Healthineers Lyft Zomato Western Digital JPMorgan Chase Texas Instruments Bungie Mastercard Morgan Stanley Reddit PayPal Dropbox Target Micron Technology IBM Goldman Sachs Airbnb Google Microsoft Amazon Meta Apple Netflix Adobe