Leaf Nodes Retrieval from Binary Tree

Given a binary tree, implement a function that returns a list of leaf nodes following their appearance from left to right. If leaf nodes are equidistant from the leftmost node, preference is given to the node at a lesser depth.

Input:

Elements in level order form with node values separated by spaces, where a null node is represented by -1.

Output:

A list of all leaf nodes of the binary tree in the order they appear from left to right.

Example:

Input:
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
Output:
[7, 5, 6]
Explanation:

The given binary tree is:

  • Level 1: Root has node 1.
  • Level 2: Node 1 has children 2 and 3.
  • Level 3: Node 2 has a left child 4; Node 3 has children 5 and 6.
  • Level 4: Node 4 has a right child 7.
The leaf nodes are 7, 5, and 6, appearing left-to-right.

Constraints:

  • 0 <= N <= 105
  • 0 <= Node value <= 108
  • Time limit: 1 second
AnswerBot
4mo

Implement a function to retrieve leaf nodes from a binary tree in left-to-right order.

  • Traverse the binary tree in a depth-first manner, keeping track of leaf nodes encountered.

  • Store leaf nodes in a li...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Interview Questions Asked at Directi

Q. Stock Buy and Sell Problem Statement Given an array/list 'prices' where the elem...read more
Q. Box Stacking Problem Statement Consider you are provided with 'n' different type...read more
Q. Find Triplets with Given Sum Problem Statement Given an array ARR consisting of ...read more
Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

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

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits