Write a program to Delete a Tree
Last Updated :
13 Jul, 2023
To delete a tree, we must traverse all the nodes of the tree and delete them one by one. So, which traversal we should use - inorder traversal, preorder traversal, or the postorder traversal? The answer is simple. We should use the postorder traversal because before deleting the parent node, we should delete its child nodes first.
We can delete the tree with other traversals also with extra space complexity but why should we go for the other traversals if we have the postorder one available which does the work without storing anything in the same time complexity.
For the following tree, nodes are deleted in the order - 4, 5, 2, 3, 1.

Note : In Java automatic garbage collection happens, so we can simply make root null to delete the tree "root = null";
Implementation:
C++
// C++ program to Delete a Tree
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
/* A binary tree node has data,
pointer to left child and
a pointer to right child */
class node
{
public:
int data;
node* left;
node* right;
/* Constructor that allocates
a new node with the given data
and NULL left and right pointers. */
node(int data)
{
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
/* This function traverses tree
in post order to delete each
and every node of the tree */
void deleteTree(node* node)
{
if (node == NULL) return;
/* first delete both subtrees */
deleteTree(node->left);
deleteTree(node->right);
/* then delete the node */
cout << "\n Deleting node: " << node->data;
delete node;
}
/* Driver code*/
int main()
{
node *root = new node(1);
root->left = new node(2);
root->right = new node(3);
root->left->left = new node(4);
root->left->right = new node(5);
deleteTree(root);
root = NULL;
cout << "\n Tree deleted ";
return 0;
}
//This code is contributed by rathbhupendra
C
// C program to Delete a Tree
#include<stdio.h>
#include<stdlib.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* This function traverses tree in post order to
to delete each and every node of the tree */
void deleteTree(struct node* node)
{
if (node == NULL) return;
/* first delete both subtrees */
deleteTree(node->left);
deleteTree(node->right);
/* then delete the node */
printf("\n Deleting node: %d", node->data);
free(node);
}
/* Driver program to test deleteTree function*/
int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
deleteTree(root);
root = NULL;
printf("\n Tree deleted ");
return 0;
}
Java
// Java program to delete a tree
// A binary tree node
class Node
{
int data;
Node left, right;
Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree
{
Node root;
/* This function traverses tree in post order to
to delete each and every node of the tree */
void deleteTree(Node node)
{
// In Java automatic garbage collection
// happens, so we can simply make root
// null to delete the tree
root = null;
}
/* Driver program to test above functions */
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
/* Print all root-to-leaf paths of the input tree */
tree.deleteTree(tree.root);
tree.root = null;
System.out.println("Tree deleted");
}
}
Python3
""" program to Delete a Tree """
# Helper function that allocates a new
# node with the given data and None
# left and right pointers.
class newNode:
# Construct to create a new node
def __init__(self, key):
self.data = key
self.left = None
self.right = None
""" This function traverses tree in post order to
to delete each and every node of the tree """
def deleteTree( node) :
if node != None:
deleteTree(node.left)
deleteTree(node.right)
del node
# Driver Code
if __name__ == '__main__':
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.left.right = newNode(5)
deleteTree(root)
root = None
print("Tree deleted ")
# This code is contributed by
# Shubham Prashar(shubhamprashar)
C#
using System;
// C# program to delete a tree
// A binary tree node
public class Node
{
public int data;
public Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
public class BinaryTree
{
public Node root;
/* This function traverses tree in post order to
to delete each and every node of the tree */
public virtual void deleteTree(Node node)
{
// In Java automatic garbage collection
// happens, so we can simply make root
// null to delete the tree
root = null;
}
/* Driver program to test above functions */
public static void Main(string[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
/* Print all root-to-leaf paths of the input tree */
tree.deleteTree(tree.root);
tree.root = null;
Console.WriteLine("Tree deleted");
}
}
// This code is contributed by Shrikant13
JavaScript
<script>
// javascript program to delete a tree
// A binary tree node
class Node {
constructor(item) {
this.data = item;
this.left = this.right = null;
}
}
var root;
/*
* This function traverses tree in post order to delete each and every node
* of the tree
*/
function deleteTree(node) {
// In javascript automatic garbage collection
// happens, so we can simply make root
// null to delete the tree
root = null;
}
/* Driver program to test above functions */
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
/* Print all root-to-leaf paths of the input tree */
deleteTree(root);
root = null;
document.write("Tree deleted");
// This code contributed by gauravrajput1
</script>
Time Complexity: O(n)
Space Complexity: If we don't consider size of stack for function calls then O(1) otherwise O(h)
The above deleteTree() function deletes the tree but doesn't change the root to NULL which may cause problems if the user of deleteTree() doesn't change root to NULL and tries to access the values using the root pointer. We can modify the deleteTree() function to take reference to the root node so that this problem doesn't occur. See the following code.
Implementation:
C++
// CPP program to Delete a Tree
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has data, pointer to left child
and a pointer to right child */
class node
{
public:
int data;
node* left;
node* right;
};
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
node* newNode(int data)
{
node* Node = new node();
Node->data = data;
Node->left = NULL;
Node->right = NULL;
return(Node);
}
/* This function is same as deleteTree()
in the previous program */
void _deleteTree(node* node)
{
if (node == NULL) return;
/* first delete both subtrees */
_deleteTree(node->left);
_deleteTree(node->right);
/* then delete the node */
cout << "Deleting node: " << node->data << endl;
delete node;
}
/* Deletes a tree and sets the root as NULL */
void deleteTree(node** node_ref)
{
_deleteTree(*node_ref);
*node_ref = NULL;
}
/* Driver code*/
int main()
{
node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
// Note that we pass the address of root here
deleteTree(&root);
cout << "Tree deleted ";
return 0;
}
// This code is contributed by rathbhupendra
C
// C program to Delete a Tree
#include<stdio.h>
#include<stdlib.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* This function is same as deleteTree() in the previous program */
void _deleteTree(struct node* node)
{
if (node == NULL) return;
/* first delete both subtrees */
_deleteTree(node->left);
_deleteTree(node->right);
/* then delete the node */
printf("\n Deleting node: %d", node->data);
free(node);
}
/* Deletes a tree and sets the root as NULL */
void deleteTree(struct node** node_ref)
{
_deleteTree(*node_ref);
*node_ref = NULL;
}
/* Driver program to test deleteTree function*/
int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
// Note that we pass the address of root here
deleteTree(&root);
printf("\n Tree deleted ");
getchar();
return 0;
}
Java
// Java program to delete a tree
/* A binary tree node has data, pointer to left child
and pointer to right child */
class Node
{
int data;
Node left, right;
Node(int d)
{
data = d;
left = right = null;
}
}
class BinaryTree
{
static Node root;
/* This function is same as deleteTree() in the previous program */
void deleteTree(Node node)
{
// In Java automatic garbage collection
// happens, so we can simply make root
// null to delete the tree
root = null;
}
/* Wrapper function that deletes the tree and
sets root node as null */
void deleteTreeRef(Node nodeRef)
{
deleteTree(nodeRef);
nodeRef=null;
}
/* Driver program to test deleteTree function */
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
/* Note that we pass root node here */
tree.deleteTreeRef(root);
System.out.println("Tree deleted");
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Python3
# Python3 program to count all nodes
# having k leaves in subtree rooted with them
# A binary tree node has data, pointer to
# left child and a pointer to right child
# Helper function that allocates a new node
# with the given data and None left and
# right pointers
class newNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
''' This function is same as deleteTree()
in the previous program '''
def _deleteTree(node):
if (node == None):
return
# first delete both subtrees
_deleteTree(node.left)
_deleteTree(node.right)
# then delete the node
print("Deleting node: ",
node.data)
node = None
# Deletes a tree and sets the root as NULL
def deleteTree(node_ref):
_deleteTree(node_ref[0])
node_ref[0] = None
# Driver code
root = [0]
root[0] = newNode(1)
root[0].left = newNode(2)
root[0].right = newNode(3)
root[0].left.left = newNode(4)
root[0].left.right = newNode(5)
# Note that we pass the address
# of root here
deleteTree(root)
print("Tree deleted ")
# This code is contributed by SHUBHAMSINGH10
C#
using System;
// C# program to delete a tree
/* A binary tree node has data, pointer to left child
and pointer to right child */
public class Node
{
public int data;
public Node left, right;
public Node(int d)
{
data = d;
left = right = null;
}
}
public class BinaryTree
{
public static Node root;
/* This function is same as deleteTree() in the previous program */
public virtual void deleteTree(Node node)
{
// In Java automatic garbage collection
// happens, so we can simply make root
// null to delete the tree
root = null;
}
/* Wrapper function that deletes the tree and
sets root node as null */
public virtual void deleteTreeRef(Node nodeRef)
{
deleteTree(nodeRef);
nodeRef = null;
}
/* Driver program to test deleteTree function */
public static void Main(string[] args)
{
BinaryTree tree = new BinaryTree();
BinaryTree.root = new Node(1);
BinaryTree.root.left = new Node(2);
BinaryTree.root.right = new Node(3);
BinaryTree.root.left.left = new Node(4);
BinaryTree.root.left.right = new Node(5);
/* Note that we pass root node here */
tree.deleteTreeRef(root);
Console.WriteLine("Tree deleted");
}
}
// This code is contributed by Shrikant13
JavaScript
<script>
// JavaScript program to delete a tree
class Node
{
constructor(data) {
this.left = null;
this.right = null;
this.data = data;
}
}
let root;
/* This function is same as deleteTree()
in the previous program */
function deleteTree(node)
{
if (node == null) return;
/* first delete both subtrees */
deleteTree(node.left);
deleteTree(node.right);
/* then delete the node */
document.write("Deleting node: " + node.data + "</br>");
}
/* Wrapper function that deletes the tree and
sets root node as null */
function deleteTreeRef(nodeRef)
{
deleteTree(nodeRef);
nodeRef=null;
}
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
/* Note that we pass root node here */
deleteTreeRef(root);
document.write("Tree deleted");
</script>
Output:
Deleting node: 4
Deleting node: 5
Deleting node: 2
Deleting node: 3
Deleting node: 1
Tree deleted
Time Complexity: O(n)
Space Complexity: If we don't consider size of stack for function calls then O(1) otherwise O(n)
Similar Reads
Delete Operation in B-Tree
A B Tree is a type of data structure commonly known as a Balanced Tree that stores multiple data items very easily. B Trees are one of the most useful data structures that provide ordered access to the data in the database. In this article, we will see the delete operation in the B-Tree. B-Trees are
15+ min read
Non-recursive program to delete an entire binary tree
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 q
10 min read
Write a function to delete a Linked List
Given a linked list, the task is to delete the linked list completely.Examples:Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> NULLOutput: NULLExplanation: Linked List is Deleted.Input: head: 1 -> 12 -> 1 -> 4 -> 1 -> NULLOutput: NULLExplanation: Linked List is Deleted.Table of C
9 min read
Iterative program to Calculate Size of a tree
Given a binary tree, the task is to find the size of the tree. The size of a tree is the number of nodes present in the tree.Example:Input: Output: 6Explanation: The number of nodes in the above binary tree is 6.Approach:The idea is to use Level Order Traversal to find the size of the tree. Initiali
5 min read
Left View of a Binary Tree
Given a Binary Tree, the task is to print the left view of the Binary Tree. The left view of a Binary Tree is a set of leftmost nodes for every level.Examples:Input: root[] = [1, 2, 3, 4, 5, N, N]Output: [1, 2, 4]Explanation: From the left side of the tree, only the nodes 1, 2, and 4 are visible.Inp
10 min read
Deletion in an AVL Tree
We have discussed AVL insertion in the previous post. In this post, we will follow a similar approach for deletion.Steps to follow for deletion. To make sure that the given tree remains AVL after every deletion, we must augment the standard BST delete operation to perform some re-balancing. Followin
15+ min read
Proto Van Emde Boas Trees | Set 4 | Deletion
Please check previous sets of Proto Van Emde Boas Tree article first. It is highly recommended.Procedure for delete: Base Case: If we reach at Proto VEB with size 2 then we will check for whether the key is present or not if yes then we assign the pointer to nullptr which will set false to it presen
14 min read
Left and Right view of a Generic Tree
Given a Generic Tree consisting of N nodes, the task is to find the left and right views of the given generic Tree. Examples: Input: 1 / \ 2 3 / \ / \ \4 5 6 7 8 Output:Left View: 1 2 4 Right View: 1 3 8 Explanation:When the tree is viewed from the left side, then the nodes which are visible is 1 2
9 min read
Deleting a binary tree using the delete keyword
A recursive and a non-recursive program to delete an entire binary tree has already been discussed in the previous posts. In this post, deleting the entire binary tree using the delete keyword in C++ is discussed. Declare a destructor function in the 'BinaryTreeNode' class which has been defined to
5 min read
Deletion in a Binary Tree
Given a binary tree, the task is to delete a given node from it by making sure that the tree shrinks from the bottom (i.e. the deleted node is replaced by the bottom-most and rightmost node). This is different from BST deletion. Here we do not have any order among elements, so we replace them with t
12 min read