Binary Tree Operations
Basic operations:
Operation | Description |
---|---|
1. Create a node | Make a new node |
2. Insert a node | Insert into the binary tree |
3. Traversals | Inorder, Preorder, Postorder |
4. Search for a node | Find a node |
5. Find height of tree | Max depth |
6. Count nodes | Total nodes, leaf nodes |
7. Delete a tree | Free all nodes |
🌳 Binary Tree Algorithms
1. Create a New Node
Algorithm:
-
Allocate memory for a new node.
-
Set the node’s
data
field to the given value. -
Set the node’s
left
andright
pointers to NULL. -
Return the newly created node.
2. Insert a Node
👉 (For a simple binary tree, level order insertion)
Algorithm:
-
If the tree is empty, create a new node and set it as root.
-
Otherwise:
-
Use a queue to perform level order traversal.
-
For each node:
-
If the left child is NULL, insert the new node as the left child and stop.
-
Else, add the left child to the queue.
-
If the right child is NULL, insert the new node as the right child and stop.
-
Else, add the right child to the queue.
-
-
3. Traversal Algorithms
(a) Inorder Traversal (Left → Root → Right)
Algorithm:
-
If the current node is not NULL:
-
Traverse the left subtree.
-
Visit (print) the current node.
-
Traverse the right subtree.
-
(b) Preorder Traversal (Root → Left → Right)
Algorithm:
-
If the current node is not NULL:
-
Visit (print) the current node.
-
Traverse the left subtree.
-
Traverse the right subtree.
-
(c) Postorder Traversal (Left → Right → Root)
Algorithm:
-
If the current node is not NULL:
-
Traverse the left subtree.
-
Traverse the right subtree.
-
Visit (print) the current node.
4. Search for a Node
Algorithm:
-
If the tree is empty, return FALSE.
-
If the current node’s data matches the key, return TRUE.
-
Recursively search the left and right subtrees.
-
If the key is found in any subtree, return TRUE.
-
Otherwise, return FALSE.
5. Find the Height of the Tree
Algorithm:
-
If the tree is empty, return -1 (or 0 depending on definition).
-
Recursively find the height of the left and right subtrees.
-
Return 1 + maximum of left and right subtree heights.
6. Count Total Number of Nodes
Algorithm:
-
If the tree is empty, return 0.
-
Recursively count the number of nodes in the left and right subtrees.
-
Total nodes = 1 (current node) + left count + right count.
7. Count Number of Leaf Nodes
Algorithm:
-
If the tree is empty, return 0.
-
If the current node is a leaf node (both left and right child are NULL), return 1.
-
Otherwise:
-
Recursively count the leaf nodes in the left and right subtrees.
-
Sum them and return.
-
8. Delete the Entire Tree
Algorithm:
-
If the current node is NULL, return.
-
Recursively delete the left subtree.
-
Recursively delete the right subtree.
-
Free the memory for the current node.
Comments
Post a Comment