Open In App

Non-recursive program to delete an entire binary tree

Last Updated : 16 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We have discussed recursive implementation to delete an entire binary tree here.
We strongly recommend you to minimize your browser and try this yourself first.
Now how to delete an entire tree without using recursion.

Method 1: Level Order Tree Traversal.

The idea is for each dequeued node from the queue, delete it after queuing its left and right nodes (if any). The solution will work as we are traverse all the nodes of the tree level by level from top to bottom, and before deleting the parent node, we are storing its children into queue that will be deleted later.
 

C++
/* Non-Recursive Program to delete an entire binary tree. */
#include <bits/stdc++.h>
using namespace std;

// A Binary Tree Node
struct Node
{
    int data;
    struct Node *left, *right;
};

/* Non-recursive function to delete an entire binary tree. */
void _deleteTree(Node *root)
{
    // Base Case
    if (root == NULL)
        return;

    // Create an empty queue for level order traversal
    queue<Node *> q;

    // Do level order traversal starting from root
    q.push(root);
    while (!q.empty())
    {
        Node *node = q.front();
        q.pop();

        if (node->left != NULL)
            q.push(node->left);
        if (node->right != NULL)
            q.push(node->right);

        free(node);
    }
}

/* Deletes a tree and sets the root as NULL */
void deleteTree(Node** node_ref)
{
  _deleteTree(*node_ref);
  *node_ref = NULL;
}

// Utility function to create a new tree Node
Node* newNode(int data)
{
    Node *temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;

    return temp;
}

// Driver program to test above functions
int main()
{
    // create a binary tree
    Node *root =  newNode(15);
    root->left = newNode(10);
    root->right = newNode(20);
    root->left->left = newNode(8);
    root->left->right = newNode(12);
    root->right->left = newNode(16);
    root->right->right = newNode(25);

    //delete entire binary tree
    deleteTree(&root);

    return 0;
}
Java
/* Non-recursive program to delete the entire binary tree */
import java.util.*;

// A binary tree node
class Node 
{
    int data;
    Node left, right;

    public Node(int data) 
    {
        this.data = data;
        left = right = null;
    }
}

class BinaryTree 
{
    Node root;

    /* Non-recursive function to delete an entire binary tree. */
    void _deleteTree() 
    {
        // Base Case
        if (root == null)
            return;

        // Create an empty queue for level order traversal
        Queue<Node> q = new LinkedList<Node>();

        // Do level order traversal starting from root
        q.add(root);
        while (!q.isEmpty()) 
        {
            Node node = q.peek();
            q.poll();

            if (node.left != null)
                q.add(node.left);
            if (node.right != null)
                q.add(node.right);
        }
    }

    /* Deletes a tree and sets the root as NULL */
    void deleteTree() 
    {
        _deleteTree();
        root = null;
    }

    // Driver program to test above functions
    public static void main(String[] args) 
    {
        // create a binary tree
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(15);
        tree.root.left = new Node(10);
        tree.root.right = new Node(20);
        tree.root.left.left = new Node(8);
        tree.root.left.right = new Node(12);
        tree.root.right.left = new Node(16);
        tree.root.right.right = new Node(25);

        // delete entire binary tree
        tree.deleteTree();
    }
}

// This code has been contributed by Mayank Jaiswal(mayank_24)
Python3
# Python program to delete an entire binary tree
# using non-recursive approach

# A binary tree node
class Node:
    
    # A constructor to create a new node
    def __init__(self, data):
        self.data = data 
        self.left = None
        self.right = None

# Non-recursive function to delete an entrie binary tree
def _deleteTree(root):
    
    # Base Case
    if root is None:
        return 

    # Create a empty queue for level order traversal
    q = []

    # Do level order traversal starting from root
    q.append(root)
    while(len(q)>0):
        node = q.pop(0)
    
        if node.left is not None:
            q.append(node.left)

        if node.right is not None:
            q.append(node.right)

        node = None
    return node

# Deletes a tree and sets the root as None
def deleteTree(node_ref):
    node_ref = _deleteTree(node_ref)
    return node_ref

# Driver program to test above function

# Create a binary tree
root = Node(15)
root.left = Node(10)
root.right = Node(20)
root.left.left = Node(8)
root.left.right = Node(12)
root.right.left = Node(16)
root.right.right = Node(25)

# delete entire binary tree
root = deleteTree(root)


# This program is contributed by Nikhil Kumar Singh(nickzuck_007)
C#
/* Non-recursive program to delete the entire binary tree */
using System;
using System.Collections.Generic;

// A binary tree node
public class Node 
{
    public int data;
    public Node left, right;

    public Node(int data) 
    {
        this.data = data;
        left = right = null;
    }
}

public class BinaryTree 
{
    Node root;

    /* Non-recursive function to
    delete an entire binary tree. */
    void _deleteTree() 
    {
        // Base Case
        if (root == null)
            return;

        // Create an empty queue for level order traversal
        Queue<Node> q = new Queue<Node>();

        // Do level order traversal starting from root
        q.Enqueue(root);
        while (q.Count != 0) 
        {
            Node node = q.Peek();
            q.Dequeue();

            if (node.left != null)
                q.Enqueue(node.left);
            if (node.right != null)
                q.Enqueue(node.right);
        }
    }

    /* Deletes a tree and sets the root as NULL */
    void deleteTree() 
    {
        _deleteTree();
        root = null;
    }

    // Driver program to test above functions
    public static void Main(String[] args) 
    {
        // create a binary tree
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(15);
        tree.root.left = new Node(10);
        tree.root.right = new Node(20);
        tree.root.left.left = new Node(8);
        tree.root.left.right = new Node(12);
        tree.root.right.left = new Node(16);
        tree.root.right.right = new Node(25);

        // delete entire binary tree
        tree.deleteTree();
    }
}

// This code has been contributed by 29AjayKumar
Javascript
<script>
/* Non-recursive program to delete the entire binary tree */

// A binary tree node
class Node 
{
    constructor(data)
    {
        this.data = data;
        this.left = this.right = null;
    }
}

let root;

/* Non-recursive function to delete an entire binary tree. */
function _deleteTree() 
{
    // Base Case
        if (root == null)
            return;
  
        // Create an empty queue for level order traversal
        let q = [];
  
        // Do level order traversal starting from root
        q.push(root);
        while (q.length != 0) 
        {
            let node = q.shift();
            
  
            if (node.left != null)
                q.push(node.left);
            if (node.right != null)
                q.push(node.right);
        }
}

    /* Deletes a tree and sets the root as NULL */
function deleteTree() 
{
    _deleteTree();
        root = null;
}

// Driver program to test above functions
root = new Node(15);
root.left = new Node(10);
root.right = new Node(20);
root.left.left = new Node(8);
root.left.right = new Node(12);
root.right.left = new Node(16);
root.right.right = new Node(25);

// delete entire binary tree
deleteTree();
        
// This code is contributed by rag2127
</script>
 

Time Complexity: O(n)

As it is a normal level order traversal and we are visiting every node just once.

Auxiliary Space: O(b)

Here b is the breadth of the tree or the maximum number of elements at any level. The extra space is required to store the elements of a level in the queue.

Method 2: Iterative post order traversal to to delete this binary tree using two stack method

First, it traverses the tree in post-order fashion, pushing nodes onto one stack and then popping them into another stack. This allows the nodes to be processed in reverse post-order sequence.

Once all nodes are in the second stack, they are popped one by one, deleted, and their values are printed. This ensures that child nodes are deleted before their parent nodes, maintaining the post-order traversal sequence.

The approach efficiently traverses the tree iteratively without using recursion, ensuring that each node is visited exactly once and deleted properly to avoid memory leaks.

C++
#include <iostream>
#include <stack>

using namespace std;

struct TreeNode {
    int value;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int val) : value(val), left(nullptr), right(nullptr) {}
};

void deleteTree(TreeNode* root) {
    if (root == nullptr)
        return;

    stack<TreeNode*> nodeStack1, nodeStack2;
    nodeStack1.push(root);

    while (!nodeStack1.empty()) {
        TreeNode* current = nodeStack1.top();
        nodeStack1.pop();
        nodeStack2.push(current);

        if (current->left)
            nodeStack1.push(current->left);
        if (current->right)
            nodeStack1.push(current->right);
    }

    while (!nodeStack2.empty()) {
        TreeNode* current = nodeStack2.top();
        nodeStack2.pop();
        cout << "Deleting node: " << current->value << endl;
        delete current; // You may need to free memory explicitly in C++
    }
}

int main() {
    // Constructing the binary tree
    TreeNode* root = new TreeNode(15);
    root->left = new TreeNode(10);
    root->right = new TreeNode(20);
    root->left->left = new TreeNode(8);
    root->left->right = new TreeNode(12);
    root->right->left = new TreeNode(16);
    root->right->right = new TreeNode(25);

    // Deleting the tree using iterative post-order traversal with two stacks
    deleteTree(root);

    return 0;
}
Java
import java.util.Stack;

class TreeNode {
    int value;
    TreeNode left, right;
    TreeNode(int val) {
        value = val;
        left = right = null;
    }
}

public class Main {
    static void deleteTree(TreeNode root) {
        if (root == null)
            return;

        Stack<TreeNode> nodeStack1 = new Stack<>();
        Stack<TreeNode> nodeStack2 = new Stack<>();
        nodeStack1.push(root);

        while (!nodeStack1.empty()) {
            TreeNode current = nodeStack1.pop();
            nodeStack2.push(current);

            if (current.left != null)
                nodeStack1.push(current.left);
            if (current.right != null)
                nodeStack1.push(current.right);
        }

        while (!nodeStack2.empty()) {
            TreeNode current = nodeStack2.pop();
            System.out.println("Deleting node: " + current.value);
            // Delete the node (free memory) here if needed
        }
    }

    public static void main(String[] args) {
        // Constructing the binary tree
        TreeNode root = new TreeNode(15);
        root.left = new TreeNode(10);
        root.right = new TreeNode(20);
        root.left.left = new TreeNode(8);
        root.left.right = new TreeNode(12);
        root.right.left = new TreeNode(16);
        root.right.right = new TreeNode(25);

        // Deleting the tree using iterative post-order traversal with two stacks
        deleteTree(root);
    }
}
Python3
class TreeNode:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

def deleteTree(root):
    if root is None:
        return

    nodeStack1 = [root]
    nodeStack2 = []

    while nodeStack1:
        current = nodeStack1.pop()
        nodeStack2.append(current)

        if current.left:
            nodeStack1.append(current.left)
        if current.right:
            nodeStack1.append(current.right)

    while nodeStack2:
        current = nodeStack2.pop()
        print("Deleting node:", current.value)
        # Delete the node (free memory) here if needed

# Constructing the binary tree
root = TreeNode(15)
root.left = TreeNode(10)
root.right = TreeNode(20)
root.left.left = TreeNode(8)
root.left.right = TreeNode(12)
root.right.left = TreeNode(16)
root.right.right = TreeNode(25)

# Deleting the tree using iterative post-order traversal with two stacks
deleteTree(root)
C#
using System;
using System.Collections.Generic;

public class TreeNode {
    public int value;
    public TreeNode left, right;
    public TreeNode(int val) {
        value = val;
        left = right = null;
    }
}

public class Program {
    static void DeleteTree(TreeNode root) {
        if (root == null)
            return;

        Stack<TreeNode> nodeStack1 = new Stack<TreeNode>();
        Stack<TreeNode> nodeStack2 = new Stack<TreeNode>();
        nodeStack1.Push(root);

        while (nodeStack1.Count > 0) {
            TreeNode current = nodeStack1.Pop();
            nodeStack2.Push(current);

            if (current.left != null)
                nodeStack1.Push(current.left);
            if (current.right != null)
                nodeStack1.Push(current.right);
        }

        while (nodeStack2.Count > 0) {
            TreeNode current = nodeStack2.Pop();
            Console.WriteLine("Deleting node: " + current.value);
            // Delete the node (free memory) here if needed
        }
    }

    public static void Main(string[] args) {
        // Constructing the binary tree
        TreeNode root = new TreeNode(15);
        root.left = new TreeNode(10);
        root.right = new TreeNode(20);
        root.left.left = new TreeNode(8);
        root.left.right = new TreeNode(12);
        root.right.left = new TreeNode(16);
        root.right.right = new TreeNode(25);

        // Deleting the tree using iterative post-order traversal with two stacks
        DeleteTree(root);
    }
}
JavaScript
class TreeNode {
    constructor(value) {
        this.value = value;
        this.left = null;
        this.right = null;
    }
}

function deleteTree(root) {
    if (!root)
        return;

    const nodeStack1 = [root];
    const nodeStack2 = [];

    while (nodeStack1.length) {
        const current = nodeStack1.pop();
        nodeStack2.push(current);

        if (current.left)
            nodeStack1.push(current.left);
        if (current.right)
            nodeStack1.push(current.right);
    }

    while (nodeStack2.length) {
        const current = nodeStack2.pop();
        console.log("Deleting node: " + current.value);
        // Delete the node (free memory) here if needed
    }
}

// Constructing the binary tree
const root = new TreeNode(15);
root.left = new TreeNode(10);
root.right = new TreeNode(20);
root.left.left = new TreeNode(8);
root.left.right = new TreeNode(12);
root.right.left = new TreeNode(16);
root.right.right = new TreeNode(25);

// Deleting the tree using iterative post-order traversal with two stacks
deleteTree(root);

Output
Deleting node: 8
Deleting node: 12
Deleting node: 10
Deleting node: 16
Deleting node: 25
Deleting node: 20
Deleting node: 15

Time Complexity: O(n)

Auxiliary Space: O(n)


 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads