9--Tree-Datastructure-19112024-112618am
9--Tree-Datastructure-19112024-112618am
AND ALGORITHMS
DR SAMABIA TEHSIN
BS (AI)
Tree
Tree is a non-linear data structure which organizes data
in a hierarchical structure, and this is a recursive
definition.
•There is one and only one path between every pair of vertices in a tree.
•The level count starts with 0 and increments by 1 at each level or step.
Tree Terminology
•Total number of edges that lies on the longest path from any leaf node to a particular node is called
as height of that node. Height of node A = 3
Height of node B = 2
•Height of a tree is the height of root node.
Height of node C = 2
•Height of all leaf nodes = 0 Height of node D = 0
Height of node E = 1
Height of node F = 0
Height of node G = 1
Height of node H = 0
Height of node I = 0
Height of node J = 0
Height of node K = 0
Tree Terminology
•Total number of edges from root node to a particular node is called as depth of that node.
•Depth of a tree is the total number of edges from root node to a leaf node in the longest path.
Linear data structures like arrays, stacks, queues, and linked list have only
one way to read the data. But a hierarchical data structure like a tree can be
traversed in different ways.
struct node {
int data;
struct node* left;
struct node* right;
}
Remember that our goal is to visit each node, so we need to visit all
the nodes in the subtree, visit the root node and visit all the nodes in
the right subtree as well.
Depending on the order in which we do this, there can be three
types of traversal
Inorder traversal
1.First, visit all the nodes in the left subtree
inorder(root->left)
display(root->data)
inorder(root->right)
Inorder traversal
We traverse the left subtree first. We also need to
remember to visit the root node and the right
subtree when this tree is done.
Let's put all this in a stack so that we remember.
Preorder traversal
1.Visit root node
2.Visit all the nodes in the left subtree
3.Visit all the nodes in the right subtree
display(root->data)
preorder(root->left)
preorder(root->right)
Postorder traversal
1.Visit all the nodes in the left subtree
2.Visit all the nodes in the right subtree
3.Visit the root node
postorder(root->left)
postorder(root->right)
display(root->data)
Code for tree traversal
Code for tree traversal
Code for tree traversal
Credits and Acknowledgements
https://www.gatevidyalay.com
https://www.programiz.com/