Tree-Data-Structures
Tree-Data-Structures
A tree data structure is a hierarchical data structure that resembles a real-world tree. The elements, called nodes,
are connected by edges, creating a parent-child relationship.
rp
by ravi prajapati
Definition and Properties
1 Hierarchical 2 Directed Edges
Structure
Edges connect nodes,
A tree organizes data in a indicating the parent-
hierarchical manner, with child relationship, and the
a root node at the top direction of the
and branches leading to relationship is defined.
child nodes.
3 No Cycles
There are no circular paths in a tree, ensuring that each
node has only one parent.
Types of Trees by Definition
1 Binary Tree 2 N-ary Tree
Each node has a maximum of two children. Each node can have up to N children.
3 General Tree 4
No restrictions on the number of children a node can have.
5 6
Terminology and Concepts
Root The topmost node in the tree.
A binary tree is a tree data There are different types of binary Common operations on binary
structure where each node can trees, such as full, complete, and trees include insertion, deletion,
have at most two children. perfect binary trees. search, and traversal.
Tree Traversal Techniques
Pre-order Traversal
Visit the root node, then the left subtree, then the
right subtree.
In-order Traversal
Visit the left subtree, then the root node, then the
right subtree.
Post-order Traversal
Visit the left subtree, then the right subtree, then the
root node.
C++ Code to Create Binary Tree
#include <iostream>
struct Node {
int data;
Node* left;
Node* right;
};
int main() {
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
return 0;
}
Algorithm for Inserting and Deleting Elements
Insertion 1
1. Start at the root node. 2. Compare the new
data with the current node's data. 3. If the new
data is less than the current node's data, move 2 Deletion
to the left child. 4. If the new data is greater than 1. Find the node to be deleted. 2. If the node is a
the current node's data, move to the right child. leaf node, simply delete it. 3. If the node has one
5. Repeat steps 2-4 until you reach a null pointer. child, replace the node with its child. 4. If the
6. Insert the new node at the null pointer node has two children, find the inorder successor
location. (the smallest node in the right subtree) and
replace the node with the successor. 5.
Recursively delete the successor from its original
position.
Applications of Tree Data Structures