Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
27 views
in Information Technology by (112k points)
How do you Construct a Full Binary Tree from its Preorder Traversal and the Preorder Traversal of its Mirror Tree?

Please log in or register to answer this question.

1 Answer

0 votes
by (112k points)

We can construct the tree recursively by dividing the preorder traversal array into two parts: one representing the left subtree and the other representing the right subtree. Then, we construct the left and right subtrees recursively. The root of the tree is the first element in the preorder traversal array. The mirror tree's preorder traversal helps in identifying the structure of the original tree.

Example Code in Python:

class TreeNode:
    def __init__(self, value):
        self.val = value
        self.left = None
        self.right = None

def construct_full_binary_tree(preorder, mirror_preorder):
    if not preorder:
        return None

    root_val = preorder[0]
    root = TreeNode(root_val)

    if len(preorder) == 1:
        return root

    # Find the index where the right subtree starts
    mirror_root_val = mirror_preorder[0]
    idx = preorder.index(mirror_root_val)

    # Construct left and right subtrees recursively
    root.left = construct_full_binary_tree(preorder[1:idx], mirror_preorder[1:idx])
    root.right = construct_full_binary_tree(preorder[idx:], mirror_preorder[idx:])

    return root

def print_preorder(node):
    if node:
        print(node.val, end=" ")
        print_preorder(node.left)
        print_preorder(node.right)

# Example usage:
preorder = [1, 2, 4, 5, 3, 6, 7]
mirror_preorder = [1, 3, 7, 6, 2, 5, 4]
root = construct_full_binary_tree(preorder, mirror_preorder)
print("Preorder Traversal of Full Binary Tree:")
print_preorder(root)
 

Explanation:

  • The TreeNode class represents a node in the binary tree.
  • The construct_full_binary_tree function takes the preorder traversal array of the original tree and its mirror tree as input and constructs the full binary tree.
  • print_preorder function is used to print the preorder traversal of the constructed full binary tree.
  • Example usage demonstrates how to use the construct_full_binary_tree function with given preorder traversals to construct the tree and print its preorder traversal.

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...