Module 4
Module 4
1. Introduction to Trees
A tree is a non-linear hierarchical data structure consisting of nodes connected by edges. It begins at a
root node and branches out to child nodes.
• Child: A node directly connected to another node moving away from the root.
2. Binary Trees
A binary tree is a tree in which each node has at most two children: left and right.
int data;
} Node;
3.1 Insertion
Insertion depends on context — full binary tree, BST, etc. In a basic tree, insert left or right manually.
return newNode;
3.2 Traversal
if (root != NULL) {
inorder(root->left);
inorder(root->right);
if (root != NULL) {
preorder(root->left);
preorder(root->right);
if (root != NULL) {
postorder(root->left);
postorder(root->right);
3.3 Searching
newNode->left = copyTree(root->left);
newNode->right = copyTree(root->right);
return newNode;
A BST is a binary tree where the left child is less than the root and the right child is greater.
else
return root;
root = root->left;
return root->data;
root = root->right;
return root->data;
5. Expression Trees
An expression tree is a binary tree representing arithmetic expressions. Leaves are operands, internal
nodes are operators.
Example: Expression (a + b) * (c - d)
/\
+ -
/\/\
a bc d
Construction and evaluation of such trees follow postorder traversal for evaluation.