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
10d

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!
Add answer anonymously...
Nagarro Senior Software Engineer 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