Preorder Traversal Problem Statement

You are provided with the root node of a binary tree comprising N nodes. Your objective is to output its preorder traversal. Preorder traversal of a binary tree is performed by visiting nodes in the following sequence:

1- Visit the root node.
2- Traverse all nodes in the left subtree of the root node.
3- Traverse all nodes in the right subtree of the root node.

Example:

Input:
The elements are provided in level order format. Input consists of space-separated values of nodes in a single line, substituting -1 for null nodes.

For example, the input for the depicted tree is:
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
Output:
[1, 2, 4, 7, 3, 5, 6]
Explanation:

For the given binary tree, the preorder traversal results in [1, 2, 4, 7, 3, 5, 6].

Constraints:

  • 1 ≤ T ≤ 10
  • 1 ≤ N ≤ 10^4
  • 1 ≤ nodeVal ≤ 10^9

Time limit: 1 sec

Note:

You are not required to print anything; the printing is handled separately. Focus on implementing the function only.

AnswerBot
4mo

Implement a function to perform preorder traversal on a binary tree given the root node.

  • Create a recursive function to traverse the tree in preorder fashion.

  • Visit the root node, then recursively trave...read more

Help your peers!
Select
Add answer anonymously...

Nagarro Senior Software Engineer interview questions & answers

A Senior Software Engineer was asked 6mo agoQ. What are functional interfaces in programming?
A Senior Software Engineer was asked 8mo agoQ. What is the Node.js event loop and how does it work?
A Senior Software Engineer was asked 10mo agoQ. Write a debounce function.

Popular interview questions of Senior Software Engineer

A Senior Software Engineer was asked 6mo agoQ1. What are functional interfaces in programming?
A Senior Software Engineer was asked 8mo agoQ2. What is the Node.js event loop and how does it work?
A Senior Software Engineer was asked 10mo agoQ3. Write a debounce function.
Nagarro Senior Software Engineer 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