Construct Binary Tree from a Parent Array

Jul 17, 2024

Lecture: Construct Binary Tree from a Parent Array

Introduction

  • Lecture Topic: Constructing a binary tree from a parent array
  • Goal: To solve the given problem in an easy and understandable manner

Problem Explanation

  • Given: A parent array where the index represents tree nodes and the elements represent their parents
  • Goal: Build a binary tree and return the root node
  • Note: If two elements have the same parent, the first element is the left child and the second is the right child

Detailed Question Understanding

  • Indexes (0 to 6) are tree nodes
  • Elements in the parent array denote the parent of the respective node
  • Parent of root node is -1
  • If an element has only one child, it is considered the left child

Example Setup

  • Parent array: [-1, 0, 0, 1, 1, 3, 5]
  • Construct the tree:
    • Root: 0 (since its parent is -1)
    • 1 and 2 are children of 0 (1 is left, 2 is right)
    • 3 and 4 are children of 1 (3 is left, 4 is right)
    • 5 is the left child of 3 (single child)
    • 6 is the left child of 5

Approach Overview

  • Traverse the parent array and make connections (parent-child relationships)
  • Use an additional array to store node pointers
  • Traverse the parent array:
    • Identify root node (-1 in parent array)
    • Build connections for left and right children

Key Steps in Code

  1. Initialize storage structures for nodes and the root
  2. Create new node for each index in the parent array
  3. Traverse the parent array and build tree based on parent-child relationships
  4. Return the root node

Code Walkthrough

# Initialize node pointers array and root
nodes = [None] * len(parent)
root = None
n = len(parent)

# Create new nodes for each index
for i in range(n):
    nodes[i] = Node(i)

# Traverse through parent array to build tree
for i in range(n):
    if parent[i] == -1:
        root = nodes[i]
    else:
        if nodes[parent[i]].left is None:
            nodes[parent[i]].left = nodes[i]
        else:
            nodes[parent[i]].right = nodes[i]

# Return root node
return root
  • Initialize nodes array and root pointer
  • Iterate through parent array:
    • On finding -1, set root node
    • Else, assign left or right children depending on availability

Summary

  • Binary tree construction from a parent array
  • Simple connections logic based on parent-child relationships
  • Resultant tree structure is built and root node is returned

Final Notes

  • Daily motivation with likes, comments, and subscriptions needed to continue making videos
  • Tutorial provided a clear understanding of converting a parent array into a binary tree structure