NOIDATUT FREE E LEARNING PLATFORM • AKTU B.TECH

Constructing a Binary Tree

A binary tree is a hierarchical data structure where each node has at most two children, referred to as the left child and the right child. It is commonly used for efficient searching and sorting, such as in Binary Search Trees and Heaps.


Theory & Explanation

Binary Tree and Binary Search Tree Operations

1. Constructing a Binary Tree from Given Traversals

A unique binary tree can be constructed if we are given two traversal sequences, provided one of them is the Inorder traversal. The other traversal must be either Preorder or Postorder.

  • From Preorder and Inorder: The Preorder sequence tells us the root node (first element). We then find this root in the Inorder sequence to determine the elements in the left and right subtrees.
  • From Postorder and Inorder: The Postorder sequence tells us the root node (last element). We then locate this root in the Inorder sequence to identify left and right subtree elements.

Example Construction (Preorder: [A, B, D, E, C], Inorder: [D, B, E, A, C])

  1. The first element of Preorder, A, is the root.
  2. In Inorder, A is at index 3. Elements [D, B, E] are to its left (Left Subtree), and [C] is to its right (Right Subtree).
  3. Recursively, the next element in Preorder, B, is the root of the left subtree [D, B, E]. In Inorder (for this subtree), B is at index 1. Elements [D] are to its left, and [E] are to its right.
  4. Continue this process until all nodes are placed.
A / \ B C / \ D E

Fig: Resulting Binary Tree

2. Binary Search Tree (BST) Operations

A Binary Search Tree is a specialized binary tree that maintains a specific order: for every node, all nodes in its left subtree have smaller values, and all nodes in its right subtree have larger values. This property enables efficient operations.

  • Searching: Start at the root. If the target value equals the root, found. If target < root, search left subtree. If target > root, search right subtree. Repeat recursively. Time Complexity: O(h), where h is height.
  • Insertion: Similar to searching. Find the appropriate null position for the new value and insert it as a leaf. Time Complexity: O(h).
  • Modification: Search for the node containing the value. Once found, update its data field. Note: Updating a key might require re-inserting the node to maintain BST property. Time Complexity: O(h).
  • Deletion: More complex. Three cases exist:
    1. Deleting a Leaf Node: Simply remove the node.
    2. Deleting a Node with One Child: Remove the node and replace it with its child.
    3. Deleting a Node with Two Children: Find the Inorder Successor (smallest value in the right subtree) or Inorder Predecessor (largest value in the left subtree). Copy this successor/predecessor value to the node and delete the original successor/predecessor node (which will have at most one child).
    Time Complexity: O(h).

3. C Implementation: BST Operations

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node left, right;
};

// Function to create a new BST node
struct Node createNode(int item) {
    struct Node temp = (struct Node)malloc(sizeof(struct Node));
    temp->data = item;
    temp->left = temp->right = NULL;
    return temp;
}

// Function to insert a new node with given data
struct Node insert(struct Node node, int data) {
    if (node == NULL) return createNode(data);
    if (data < node->data)
        node->left = insert(node->left, data);
    else if (data > node->data)
        node->right = insert(node->right, data);
    return node;
}

// Function to search for a given key in BST
struct Node search(struct Node root, int key) {
    if (root == NULL || root->data == key)
        return root;
    if (root->data < key)
        return search(root->right, key);
    return search(root->left, key);
}

// Function to find the minimum value node in a given BST
struct Node minValueNode(struct Node node) {
    struct Node current = node;
    while (current && current->left != NULL)
        current = current->left;
    return current;
}

// Function to delete a key from BST and return new root
struct Node deleteNode(struct Node root, int data) {
    if (root == NULL) return root;
    if (data < root->data)
        root->left = deleteNode(root->left, data);
    else if (data > root->data)
        root->right = deleteNode(root->right, data);
    else {
        // Node with only one child or no child
        if (root->left == NULL) {
            struct Node temp = root->right;
            free(root);
            return temp;
        }
        else if (root->right == NULL) {
            struct Node temp = root->left;
            free(root);
            return temp;
        }
        // Node with two children: Get the inorder successor (smallest in the right subtree)
        struct Node temp = minValueNode(root->right);
        // Copy the inorder successor's content to this node
        root->data = temp->data;
        // Delete the inorder successor
        root->right = deleteNode(root->right, temp->data);
    }
    return root;
}

// Function to modify a key in BST
void modify(struct Node root, int oldKey, int newKey) {
    struct Node target = search(root, oldKey);
    if(target != NULL) {
        target->data = newKey; // Note: This simplistic modification may violate BST property if not careful
    }
}

// Utility function for inorder traversal
void inorder(struct Node root) {
    if (root != NULL) {
        inorder(root->left);
        printf("%d ", root->data);
        inorder(root->right);
    }
}

int main() {
    struct Node* root = NULL;
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);

    printf("Inorder traversal of the given BST: ");
    inorder(root);
    printf("\n");

    printf("\nDelete 20\n");
    root = deleteNode(root, 20);
    printf("Inorder traversal after deletion: ");
    inorder(root);
    printf("\n");

    printf("\nDelete 30\n");
    root = deleteNode(root, 30);
    printf("Inorder traversal after deletion: ");
    inorder(root);
    printf("\n");

    printf("\nDelete 50\n");
    root = deleteNode(root, 50);
    printf("Inorder traversal after deletion: ");
    inorder(root);
    printf("\n");

    printf("\nSearch for 40: ");
    if(search(root, 40)) printf("Found\n"); else printf("Not Found\n");

    printf("\nModify 40 to 45\n");
    modify(root, 40, 45);
    printf("Inorder traversal after modification: ");
    inorder(root);
    printf("\n");

    return 0;
}

Expected Output (C):


Inorder traversal of the given BST: 20 30 40 50 60 70 80 

Delete 20
Inorder traversal after deletion: 30 40 50 60 70 80 

Delete 30
Inorder traversal after deletion: 40 50 60 70 80 

Delete 50
Inorder traversal after deletion: 40 60 70 80 

Search for 40: Found

Modify 40 to 45
Inorder traversal after modification: 45 60 70 80 

5. Python Implementation: BST Operations

class Node:
    def __init__(self, key):
        self.left = None
        self.right = None
        self.val = key

def insert(root, key):
    if root is None:
        return Node(key)
    if key < root.val:
        root.left = insert(root.left, key)
    else:
        root.right = insert(root.right, key)
    return root

def search(root, key):
    if root is None or root.val == key:
        return root
    if root.val < key:
        return search(root.right, key)
    return search(root.left, key)

def min_value_node(node):
    current = node
    while(current.left is not None):
        current = current.left
    return current

def delete_node(root, key):
    if root is None:
        return root
    if key < root.val:
        root.left = delete_node(root.left, key)
    elif(key > root.val):
        root.right = delete_node(root.right, key)
    else:
        if root.left is None:
            temp = root.right
            root = None
            return temp
        elif root.right is None:
            temp = root.left
            root = None
            return temp
        temp = min_value_node(root.right)
        root.val = temp.val
        root.right = delete_node(root.right, temp.val)
    return root

def modify(root, old_key, new_key):
    target = search(root, old_key)
    if target:
        target.val = new_key

def inorder(root):
    if root:
        inorder(root.left)
        print(root.val, end=" ")
        inorder(root.right)

# Driver Code
if __name__ == '__main__':
    root = None
    root = insert(root, 50)
    root = insert(root, 30)
    root = insert(root, 20)
    root = insert(root, 40)
    root = insert(root, 70)
    root = insert(root, 60)
    root = insert(root, 80)

    print("Inorder traversal of the given BST: ", end="")
    inorder(root)
    print()

    print("\nDelete 20")
    root = delete_node(root, 20)
    print("Inorder traversal after deletion: ", end="")
    inorder(root)
    print()

    print("\nDelete 30")
    root = delete_node(root, 30)
    print("Inorder traversal after deletion: ", end="")
    inorder(root)
    print()

    print("\nDelete 50")
    root = delete_node(root, 50)
    print("Inorder traversal after deletion: ", end="")
    inorder(root)
    print()

    print(f"\nSearch for 40: ", end="")
    if search(root, 40): print("Found") else: print("Not Found")

    print("\nModify 40 to 45")
    modify(root, 40, 45)
    print("Inorder traversal after modification: ", end="")
    inorder(root)
    print()

Expected Output (Python):


Inorder traversal of the given BST: 20 30 40 50 60 70 80 

Delete 20
Inorder traversal after deletion: 30 40 50 60 70 80 

Delete 30
Inorder traversal after deletion: 40 50 60 70 80 

Delete 50
Inorder traversal after deletion: 40 60 70 80 

Search for 40: Found

Modify 40 to 45
Inorder traversal after modification: 45 60 70 80 
  

Diagrams

constructing-a-binary-tree - Diagram

constructing-a-binary-tree - Diagram

Advertisement
Advertisement