0% found this document useful (0 votes)
2 views17 pages

Dsa Trees

A tree in data structures is defined by properties such as root, parent-child relationships, leaf nodes, edges, and subtrees. Binary trees are a specific type of tree where each node has at most two children, and operations include insertion, deletion, traversal, and searching. Various types of binary trees exist, including full, complete, and perfect binary trees, with traversal methods categorized into breadth-first and depth-first searches.

Uploaded by

Nikhil Sn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views17 pages

Dsa Trees

A tree in data structures is defined by properties such as root, parent-child relationships, leaf nodes, edges, and subtrees. Binary trees are a specific type of tree where each node has at most two children, and operations include insertion, deletion, traversal, and searching. Various types of binary trees exist, including full, complete, and perfect binary trees, with traversal methods categorized into breadth-first and depth-first searches.

Uploaded by

Nikhil Sn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Trees

What Is a Tree in DSA?


A tree is defined by the following properties:
Root: The topmost node in the tree, which serves as the starting point for
traversals.
Parent-Child Relationship: Each node (except the root) has exactly one parent
and zero or more children.
Leaf Nodes: Nodes that do not have any children.
Edges: The connections between nodes.
Subtree: A tree formed by a node and its descendants.

Basic Operations on Trees


Common operations performed on trees include:
 Insertion: Adding a node to the tree.
 Deletion: Removing a node from the tree.
 Traversal: Visiting all the nodes in a specific order (e.g., in-order, pre-
order, post-order)
 Searching: Finding a node with a specific value.
 Balancing: Rearranging the tree to maintain its balanced property (e.g.,
AVL or Red-Black trees)
Binary Tree is a non-linear and hierarchical data structure where each node
has at most two children referred to as the left child and the right child. The
topmost node in a binary tree is called the root, and the bottom-most nodes are
called leaves

/ Structure of each node of the tree.


struct Node {
int data;
struct Node* left;
struct Node* right;
};

// Note : Unlike other languages, C does not support


// Object Oriented Programming. So we need to write
// a separat method for create and instance of tree node
struct Node* newNode(int item) {
struct Node* temp =
(struct Node*)malloc(sizeof(struct Node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}

Example for Creating a Binary Tree


Here’s an example of creating a Binary Tree with four nodes (2, 3, 4, 5)
Properties of Binary Tree
 The maximum number of nodes at level L of a binary tree is 2L
 The maximum number of nodes in a binary tree of height H is 2H – 1
 Total number of leaf nodes in a binary tree =
total number of nodes with 2 children + 1
 In a Binary Tree with N nodes, the minimum possible height or the minimum
number of levels is Log2(N+1)
 A Binary Tree with L leaves has at least | Log2L |+ 1 levels

Binary Tree Applications

 For easy and quick access to data


 In router algorithms
 To implement heap data structure
 Syntax tree
Full Binary Tree

A full Binary tree is a special type of binary tree in which every parent
node/internal node has either two or no children.

It is also known as a proper binary tree.

Binary Search Tree(BST)

Binary search tree is a data structure that quickly allows us to maintain a sorted
list of numbers.

 It is called a binary tree because each tree node has a maximum of two children.

 It is called a search tree because it can be used to search for the presence of a
number in O(log(n)) time.
The properties that separate a binary search tree from a regular binary tree is
1. All nodes of left subtree are less than the root node

2. All nodes of right subtree are more than the root node

3. Both subtrees of each node are also BSTs i.e. they have the above two properties
A tree
having a right subtree with one value smaller than the root is shown to
demonstrate that it is not a valid binary search tree
The binary tree on the right isn't a binary search tree because the right subtree of
the node "3" contains a value smaller than it.

There are two basic operations that you can perform on a binary search tree:

Search Operation

The algorithm depends on the property of BST that if each left subtree has values
below root and each right subtree has values above the root.

If the value is below the root, we can say for sure that the value is not in the right
subtree; we need to only search in the left subtree and if the value is above the
root, we can say for sure that the value is not in the left subtree; we need to only
search in the right subtree.

Algorithm:

If root == NULL
return NULL;
If number == root->data
return root->data;
If number < root->data
return search(root->left)
If number > root->data
return search(root->right)

Let us try to visualize this with a diagram.

4 is not found so,


traverse

through the left subtree of 8

4 is not found so, traverse


through the right subtree of 3
4 is not found so, traverse
through the left subtree of 64 is found

Insert 4 as a left child of 6

We have attached the node but we still have to exit from the function without
doing any damage to the rest of the tree. This is where the return node; at the end
comes in handy. In the case of NULL, the newly created node is returned and
attached to the parent node, otherwise the same node is returned without any
change as we go up until we return to the root.
This makes sure that as we move back up the tree, the other node connections
aren't changed.
Image showing
the importance of returning the root element at the end so that the elements don't
lose their position during the upward recursion step.

(important)
Tree Data Structure Terminologies
Terminology Description Example from Diagram

‘1’, ‘2’, ‘3’ are the node in the


Node Each vertex of a tree is a node.
tree.

Node ‘1’ is the topmost root


Root Topmost node of a tree.
node.

Node ‘2’ is the parent of ‘5’


The node has an edge-sharing to a child
Parent Node and ‘6’, and Node ‘3’ is the
node.
parent of ‘7’.

The sub-node of a parent node is the ‘5’ and ‘6’ is the children of
Child Node
child node. ‘2’.

The last node which have any subnode ‘5’, ‘6’, ‘9’ and ‘8’ are leaf
Leaf
is the leaf node. nodes.

The link between ‘1’ and ‘2’,


Edge Connecting link between two nodes. ‘2’ and ‘5’, ‘2’ and ‘6’ are
edges

‘5’ and ‘6’ are siblings with ‘2’


Siblings Nodes with the same parent are siblings.
as their parent.

The height of a tree is the length of the


longest path from the root to a leaf node. The height of ‘1’ is 3. (longest
Height
It is calculated with the total number of path is 1-3-7-9)
edges.

The number of edges from the root node


to that node is called the Depth of that The depth of root node ‘1’ is
Depth
node. the height of ‘1’ – 1 = 2
Depth of a tree = Height of tree – 1

Each step from top to bottom is called a


‘1’ or root node is at level 0,
Level. If the root node is at level 0, its
Level ‘2’, ‘3’, and ‘4’ is at level 1,
next child node is at level 1, its
and so on.
grandchild is at level 2, and so on.
Descendants of a node represent a Nodes ‘2’, ‘5’, and ‘6’
Sub-Tree
subtree. represent a sub-tree.

Degree of The degree of a node represents the total The degree of ‘2’ is 2 (‘5’ and
Node number of children in it. ‘6’). The degree of ‘4’ is 1.

Array Implementation of Binary Trees

To avoid the cost of all the shifts in memory that we get from using Arrays, it is
useful to implement Binary Trees with pointers from one element to the next, just
like Binary Trees are implemented before this point, especially when the Binary
Tree is modified often.

But in case we read from the Binary Tree a lot more than we modify it, an Array
implementation of a Binary Tree can make sense as it needs less memory, it can
be easier to implement, and it can be faster for certain operations due to cache
locality.

#include <stdio.h>

#define ARRAY_SIZE 15 // Define the size of the array

char* get_data(char binaryTreeArray[], int index);


int left_child_index(int index);
int right_child_index(int index);

int main() {
char binaryTreeArray[ARRAY_SIZE] = {'R', 'A', 'B', 'C', 'D', 'E', 'F', '\0', '\0',
'\0', '\0', '\0', '\0', 'G', '\0'};

int rightChild = right_child_index(0);


int leftChildOfRightChild = left_child_index(rightChild);
char* data = get_data(binaryTreeArray, leftChildOfRightChild);

if (data != NULL) {
printf("root.right.left.data: %c\n", *data);
} else {
printf("No data found.\n");
}

return 0;
}

char* get_data(char binaryTreeArray[], int index) {


if (index >= 0 && index < ARRAY_SIZE) {
return &binaryTreeArray[index];
}
return NULL;
}

int left_child_index(int index) {


return 2 * index + 1;
}

int right_child_index(int index) {


return 2 * index + 2;
}

A binary tree is a tree data structure in which each parent node can have at most
two children. Each node of a binary tree consists of three items:

 data item

 address of left child


 address of right child

Types of Binary Trees

There are different variants, or types, of Binary Trees worth discussing to get a
better understanding of how Binary Trees can be structured.

The different kinds of Binary Trees are also worth mentioning now as these words
and concepts will be used later in the tutorial.

Below are short explanations of different types of Binary Tree structures, and
below the explanations are drawings of these kinds of structures to make it as
easy to understand as possible.

A balanced Binary Tree has at most 1 in difference between its left and right
subtree heights, for each node in the tree.

A complete Binary Tree has all levels full of nodes, except the last level, which
is can also be full, or filled from left to right. The properties of a complete Binary
Tree means it is also balanced.

A full Binary Tree is a kind of tree where each node has either 0 or 2 child nodes.

A perfect Binary Tree has all leaf nodes on the same level, which means that all
levels are full of nodes, and all internal nodes have two child nodes.The properties
of a perfect Binary Tree means it is also full, balanced, and complete.
Binary Tree Traversal

Going through a Tree by visiting every node, one node at a time, is called
traversal.

There are two main categories of Tree traversal methods:

Breadth First Search (BFS) is when the nodes on the same level are visited
before going to the next level in the tree. This means that the tree is explored in a
more sideways direction.

Depth First Search (DFS) is when the traversal moves down the tree all the way
to the leaf nodes, exploring the tree branch by branch in a downwards direction.

There are three different types of DFS traversals:

 pre-order
 in-order
 post-order
Pre-order Traversal of Binary Trees

#include <stdio.h>
#include <stdlib.h>

typedef struct TreeNode {


char data;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;

TreeNode* createNewNode(char data) {


TreeNode* newNode = (TreeNode*)malloc(sizeof(TreeNode));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

void preOrderTraversal(TreeNode* root) {


if (root == NULL) {
return;
}
printf("%c, ", root->data);
preOrderTraversal(root->left);
preOrderTraversal(root->right);
}
int main() {
TreeNode* root = createNewNode('R');
TreeNode* nodeA = createNewNode('A');
TreeNode* nodeB = createNewNode('B');
TreeNode* nodeC = createNewNode('C');
TreeNode* nodeD = createNewNode('D');
TreeNode* nodeE = createNewNode('E');
TreeNode* nodeF = createNewNode('F');
TreeNode* nodeG = createNewNode('G');

root->left = nodeA;
root->right = nodeB;

nodeA->left = nodeC;
nodeA->right = nodeD;

nodeB->left = nodeE;
nodeB->right = nodeF;

nodeF->left = nodeG;

// Traverse
preOrderTraversal(root);

free(nodeG);
free(nodeF);
free(nodeE);
free(nodeB);
free(nodeC);
free(nodeD);
free(nodeA);
free(root);

return 0;
}
IN -order Traversal of Binary Trees

Post-order Traversal of Binary Trees


Pre-order, NLR

1. Visit the current node (in the figure: position red).


2. Recursively traverse the current node's left subtree.
3. Recursively traverse the current node's right subtree.
Post-order, LRN

1. Recursively traverse the current node's left subtree.


2. Recursively traverse the current node's right subtree.
3. Visit the current node (in the figure: position blue).
In-order, LNR

1. Recursively traverse the current node's left subtree.


2. Visit the current node (in the figure: position green).
3. Recursively traverse the current node's right subtree.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy