ADVANCED DATA STRUCTURES PROGRAM • LEVEL 17 — ADVANCED HEAPS

Meld Two Leftist Heaps

Learn how to meld two leftist heaps using a clear C program.

AdvancedHeap variantsPriority queue

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
5 10 20 30 40 50

COMPLETE C PROGRAM

Complete C implementation

ads-leftist-heap-merge.c
Open in compiler
#include <stdio.h>
#include <stdlib.h>

struct Node{int key,npl;struct Node*left,*right;};int rank_node(struct Node*n){return n?n->npl:-1;}struct Node*new_node(int key){struct Node*n=calloc(1,sizeof*n);if(!n)exit(EXIT_FAILURE);n->key=key;return n;}struct Node*merge(struct Node*a,struct Node*b){if(!a)return b;if(!b)return a;if(a->key>b->key){struct Node*t=a;a=b;b=t;}a->right=merge(a->right,b);if(rank_node(a->left)<rank_node(a->right)){struct Node*t=a->left;a->left=a->right;a->right=t;}a->npl=rank_node(a->right)+1;return a;}

int main(void)
{
    struct Node *first=NULL,*second=NULL; int a[]={10,30,50},b[]={5,20,40};
    for(int i=0;i<3;i++){first=merge(first,new_node(a[i]));}
    for(int i=0;i<3;i++){second=merge(second,new_node(b[i]));}
    struct Node *root=merge(first,second); while(root){printf("%d%c",root->key,root->left||root->right?' ':'\n');struct Node *old=root;root=merge(root->left,root->right);free(old);}return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

5 10 20 30 40 50
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Recursively meld right paths and swap children to preserve the leftist null-path-length rule.
  3. Display the computed result.

Recursively meld right paths and swap children to preserve the leftist null-path-length rule.

EFFICIENCY

Time and space complexity

Time complexity

O(log n) meld

Auxiliary space

O(log n)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.