Construct Tree from Preorder Traversal

Given a list of integers pre[] of size n, representing the preorder traversal of a special binary tree where each node has 0 or 2 children, and a boolean array isLeaf[] indicating if a node is a leaf. Write a function to construct the binary tree from the given arrays and return the root node.

Input:

The input consists of multiple test cases, each containing:

  • An integer t representing the number of test cases.
  • For each test case:
    • An integer n: the number of nodes in the binary tree.
    • A list of integers pre[] of length n, representing the preorder traversal.
    • A list isLeaf[], where 0 signifies a non-leaf node and 1 signifies a leaf node.

Output:

Return the root node of the constructed tree for each test case. Print the output in a new line for each test case.

Example:

Input:
t = 1
n = 7
pre = [1, 2, 4, 5, 3, 6, 7]
isLeaf = [0, 0, 1, 1, 0, 1, 1]
Output:
Root node of the constructed tree

Constraints:

  • 1 ≤ T ≤ 50
  • 1 ≤ N ≤ 10^3
  • -10^9 ≤ pre[i] ≤ 10^9
Note:
You are not required to print anything; just implement the function to construct the tree using the given arrays.
AnswerBot
1mo

Construct a binary tree from preorder traversal and leaf node information.

  • Create a binary tree using preorder traversal and leaf node information

  • Use recursion to build the tree

  • Handle both leaf and non...read more

Help your peers!
Add answer anonymously...
Oracle Full Stack 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