DS Unit 4
DS Unit 4
Unit 4
Unit 4 Topics
Trees: Introduction
Binary Trees
Binary Tree
1. Array Representation
2. Linked List Representation
Array Representation
● A complete binary tree is just like a full binary tree, but with
two major differences:
• Every level except the last level must be completely filled.
• All the leaf elements must lean towards the left.
• The last leaf element might not have a right sibling i.e. a
complete binary tree doesn’t have to be a full binary tree.
Algorithm Preorder(tree)
Algorithm Postorder(tree)
Algorithm: buildTree()
1. Pick an element from Preorder. Increment a Preorder Index
Variable (preIndex in below code) to pick the next element in
the next recursive call.
2. Create a new tree node tNode with the data as the picked
element.
3. Find the picked element’s index in Inorder. Let the index be
inIndex.
4. Call buildTree for elements before inIndex and make the built
tree as a left subtree of tNode.
5. Call buildTree for elements after inIndex and make the built
tree as a right subtree of tNode.
6. return tNode.
Complexity Analysis
Time Complexity Analysis:
● In general, if we want to analyze the time complexity of a tree
traversal then we have to think in terms of the number of nodes
visited.
● Hence, if a tree has n nodes, then each node is visited only
once in traversal (inorder, preorder and postorder) and
hence the complexity of the inorder traversal of the binary tree
is O(n) .
Space Complexity Analysis:
● For a tree of height h, space complexity is O(h) since space
complexity of recursion is always the height / depth of
recursion.
● For skewed trees, the height of the tree may be equal to the
number of nodes in the tree, hence leading to an overall space
complexity of O(n)
Excellence and Service
CHRIST
Deemed to be University
AVL Tree
AVL tree
● If balance factor of any node is 1,
it means that the left sub-tree is
one level higher than the right
sub-tree.
● If balance factor of any node is 0,
it means that the left sub-tree
and right sub-tree contain equal
height.
● If balance factor of any node is
1, it means that the left sub-tree
is one level lower than the right
sub-tree.
● An AVL tree is given in the given
figure. We can see that, balance
factor associated with each node
is in between 1 Excellence
and and1.Service
CHRIST
Deemed to be University
● Complete graph: Every node connected to all other nodes. Edges: n(n-1)/2
● Weighted graph: Assigned some value for cost of travelling edge
● Adjacent nodes: Nodes connected via an edge
Excellence and Service
CHRIST
Deemed to be University
Now, Stack becomes empty, which means we have visited all the
nodes and our DFS traversal ends
Excellence and Service