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 lengthn
, representing the preorder traversal. - A list
isLeaf[]
, where0
signifies a non-leaf node and1
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.
Be the first one to answer
Add answer anonymously...
Top Oracle Full Stack Developer interview questions & answers
Popular interview questions of Full Stack Developer
Stay ahead in your career. Get AmbitionBox app
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
Get AmbitionBox app