Extracting Leaf Nodes from a Binary Tree

Given a binary tree, develop a solution to retrieve a list of all the leaf nodes in the order they appear from left to right. If two leaf nodes are equidistant from the leftmost node, prioritize the one with lesser depth or, if necessary, the smaller node data.

Input:

Elements in level order format. The input consists of values of nodes separated by spaces in a single line. A placeholder of -1 indicates a null node.

Output:

Return a list containing all the leaf nodes of the binary tree, listed from left to right.

Example:

Consider the input that represents the binary tree depicted in the image below:

1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1

Explanation:

The root is 1.
Level 2 has nodes 2 (left) and 3 (right).
Level 3 has nodes 4 (left child of 2), 5 and 6 (children of 3).
Level 4 ends with node 7 (right child of 4) and nulls.
This sequence represents the tree structure where nodes are level-order traversed.

Constraints:

  • 0 <= N <= 105
  • 0 <= Node Value <= 108
  • 'N' is the total count of nodes in the BinaryTree.
  • Time Limit: 1 second
Note:
The listed format illustrates input preparation for a given tree structure. The complete sequence will be provided as a single line separated by spaces.
Be the first one to answer
Add answer anonymously...
AlphaSense Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter