Data Structure 21 + 22
Data Structure 21 + 22
Lecture 21 + 22
Instructor: Tayyba Khalid
Content:
Trees
Types of trees
Implementation of trees
Binary trees
Transversal of trees
Binary Search Trees
AVL trees
M-way trees
Trees
■ A tree is a non linear data structure. Each object of tree start with root
and extend into branches.
■ tree is a hierarchical data structure that consists of nodes connected
by edges.
■ It has the following properties:
• Root: The top node in the tree.
• Parent: A node that has child nodes.
• Child: A node that is a descendant of a parent node.
• Leaf: A node with no children.
• Height: The length of the longest path from the root to a leaf.
• Depth: The number of edges from the root to the node
• Sibling: Children of the same parent node are called siblings.
Types:
•General Trees:
•Binary Trees:
•Transversal of trees
•AVL Trees:
•M-way Trees:
•Red-Black Trees:
General Trees:
A type of self-balancing binary search tree where the heights of the two child
subtrees of every node differ by at most one.
M-way Trees:
■ Trees where each node can have more than two children (e.g., B-trees).
Red-Black Trees:
■ A self-balancing binary search tree with additional properties related to node
color. Every node has a color either red or black.
■ The root of the tree is always black.
■ There are no two adjacent red nodes (A red node cannot have a red parent or
red child).
■ Every path from a node (including root) to any of its descendants’ NULL nodes
has the same number of black nodes.
■ All leaf (NULL) nodes are black nodes.
Implementation of Trees
A type of binary tree where the left subtree contains values smaller than the parent
node, and the right subtree contains values greater than the parent node.
Binary Search Trees (BST):
■ The below steps are followed while we try to insert a node into a binary search tree:
• Initilize the current node (say, currNode or node) with root node
• Move left if the key is less than or equal to the current node value.
• Attach the new key as a left or right child based on the comparison with the leaf
node’s value.
Working Insertion
Construction
16 , 19 , 15 , 9 , 8 , 66 , 12 , 61
Advantages Disadvantages
■ Efficient searching: ■ Imbalanced trees: If a tree
is not balanced, it can result
■ Flexible size:
in uneven search times
■ Fast insertion and deletion
■ Complexity: Unlike Arrays
and Linked Lists, Trees can be
complex data structures, and
they can be difficult to
understand and implement
correctly.