0% found this document useful (0 votes)
51 views11 pages

Week11 1

A tree is a hierarchical data structure consisting of nodes connected by edges where each node stores a value and references to other nodes. A tree has a root node, branches, and leaf nodes. It is considered non-linear because data is not stored sequentially. Key terminology includes parent/child nodes, root, leaf, internal nodes. Trees allow for efficient search, sorting, and representation of hierarchical data. Binary trees restrict nodes to at most two children each and binary search trees provide efficient search by enforcing an ordering of node values.

Uploaded by

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

Week11 1

A tree is a hierarchical data structure consisting of nodes connected by edges where each node stores a value and references to other nodes. A tree has a root node, branches, and leaf nodes. It is considered non-linear because data is not stored sequentially. Key terminology includes parent/child nodes, root, leaf, internal nodes. Trees allow for efficient search, sorting, and representation of hierarchical data. Binary trees restrict nodes to at most two children each and binary search trees provide efficient search by enforcing an ordering of node values.

Uploaded by

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

Week 11

What is a Tree data structure?

A tree is non-linear and a hierarchical data structure consisting of a collection of


nodes such that each node of the tree stores a value and a list of references to other
nodes (the “children”).
Tree data structure has roots, branches, and leaves connected with one another.

Recursive Definition:
A tree consists of a root, and zero or more subtrees T 1, T2, … , Tk such that there is
an edge from the root of the tree to the root of each subtree.
Why Tree is considered a non-linear data structure?

The data in a tree are not stored in a sequential manner i.e, they are not stored
linearly. Instead, they are arranged on multiple levels or we can say it is a
hierarchical structure. For this reason, the tree is considered to be a non-linear data
structure.

Basic Terminologies In Tree Data Structure:

 Parent Node: The node which is a predecessor of a node is called the parent
node of that node. {2} is the parent node of {6, 7}.
 Child Node: The node which is the immediate successor of a node is called the
child node of that node. Examples: {6, 7} are the child nodes of {2}.
 Root Node: The topmost node of a tree or the node which does not have any
parent node is called the root node. {1} is the root node of the tree. A non-empty
tree must contain exactly one root node and exactly one path from the root to all
other nodes of the tree.
 Leaf Node or External Node: The nodes which do not have any child nodes are
called leaf nodes. {6, 14, 8, 9, 15, 16, 4, 11, 12, 17, 18, 19} are the leaf nodes of
the tree.
 Ancestor of a Node: Any predecessor nodes on the path of the root to that node
are called Ancestors of that node. {1, 2} are the parent nodes of the node {7}
 Descendant: Any successor node on the path from the leaf node to that node. {7,
14} are the descendants of the node. {2}.
 Sibling: Children of the same parent node are called siblings. {8, 9, 10} are
called siblings.
 Level of a node: The count of edges on the path from the root node to that node.
The root node has level 0.
 Internal node: A node with at least one child is called Internal Node.
 Neighbour of a Node: Parent or child nodes of that node are called neighbors of
that node.
 Subtree: Any node of the tree along with its descendant.

Properties of a Tree:

 Number of edges: An edge can be defined as the connection between two nodes.
If a tree has N nodes then it will have (N-1) edges. There is only one path from
each node to any other node of the tree.
 Depth of a node: The depth of a node is defined as the length of the path from
the root to that node. It can also be defined as the number of edges in the path
from the root of the tree to the node.
 Height of a node: The height of a node can be defined as the length of the
longest path from the node to a leaf node of the tree.
 Height of the Tree: The height of a tree is the length of the longest path from the
root of the tree to a leaf node of the tree.
 Degree of a Node: The total count of subtrees attached to that node is called the
degree of the node. The degree of a leaf node must be 0. The degree of a tree is
the maximum degree of a node among all the nodes in the tree.

Some more properties are:
 Traversing in a tree is done by depth first search and breadth first search
algorithm.
 It has no loop and no circuit
 It has no self-loop
 Its hierarchical model.

Basic Operation Of Tree:

Create – create a tree in data structure.


Insert − Inserts data in a tree.
Search − Searches specific data in a tree to check it is present or not.
Preorder Traversal – perform Traveling a tree in a pre-order manner in data structure
In order Traversal – perform Traveling a tree in an in-order manner.
Post order Traversal –perform Traveling a tree in a post-order manner.
Example of Tree data structure

Here,
Node A is the root node
B is the parent of D and E
D and E are the siblings
D, E, and F are the leaf nodes
A and B are the ancestors of E
Few examples on Tree Data Structure: A code to demonstrate few of the above
terminologies has been described below:

Types of Tree data structures


The different types of tree data structures are as follows:
1. General tree
A general tree data structure has no restriction on the number of nodes. It means that
a parent node can have any number of child nodes.
2. Binary tree
A node of a binary tree can have a maximum of two child nodes. In the given tree
diagram, node B, D, and F are left children, while E, C, and G are the right children.
3. Balanced tree
If the height of the left sub-tree and the right sub-tree is equal or differs at most by 1,
the tree is known as a balanced tree.

Balanced Tree Unbalanced Tree

4. Binary search tree


As the name implies, binary search trees are used for various searching and sorting
algorithms. It is a non-linear data structure. It shows that the value of the left node is
less than its parent, while the value of the right node is greater than its parent.
Why Use Trees?
1. One reason to use trees might be because you want to store information that
naturally forms a hierarchy. For example, the file system on a computer:
file system
———–
user <– root
/ \
... home
/ \
ugrad course
/ / | \
... cs101 cs112 cs113
2. Trees (with some ordering e.g., BST) provide moderate access/search (quicker
than Linked List and slower than arrays).
3. Trees provide moderate insertion/deletion (quicker than Arrays and slower than
Unordered Linked Lists).
4. Like Linked Lists and unlike Arrays, Trees don’t have an upper limit on the
number of nodes as nodes are linked using pointers.

Main applications of trees include:


1. Manipulate hierarchical data.
2. Make information easy to search .
3. Manipulate sorted lists of data.
4. As a workflow for compositing digital images for visual effects.
5. Router algorithms
6. Form of multi-stage decision-making.

Binary Tree: A tree whose elements have at most 2 children is called a binary tree.
Since each element in a binary tree can have only 2 children, we typically name
them the left and right child.
Binary Tree Representation: A tree is represented by a pointer to the topmost node
of the tree. If the tree is empty, then the value of the root is NULL.
A Tree node contains the following parts.
1. Data
2. Pointer to the left child
3. Pointer to the right child

# A Python class that represents


# an individual node in a Binary Tree
class Node:
def __init__(self,key):
self.left = None
self.right = None
self.val = key

Basic Operation On Binary Tree:


 Inserting an element.
 Removing an element.
 Searching for an element.
 Traversing an element. There are three types of traversals in a binary tree which
will be discussed ahead.

Applications of Binary Tree:


 In compilers, Expression Trees are used which is an application of binary tree.
 Huffman coding trees are used in data compression algorithms.
 Priority Queue is another application of binary tree that is used for searching
maximum or minimum in O(logN) time complexity.
Binary Tree Traversals:
 PreOrder Traversal: Here, the traversal is: root – left child – right child. It
means that the root node is traversed first then its left child and finally the right
child.
 InOrder Traversal: Here, the traversal is: left child – root – right child. It
means that the left child is traversed first then its root node and finally the right
child.
 PostOrder Traversal: Here, the traversal is: left child – right child – root. It
means that the left child is traversed first then the right child and finally its root
node.
Let us traverse the following tree with all the three traversal methods:
Tree
________________

1 //Root Node
/\
2 3
/\ /\
4 5 6 7 //Leaf Nodes
PreOrder Traversal of the above tree: 1-2-4-5-3-6-7
InOrder Traversal of the above tree: 4-2-5-1-6-3-7
PostOrder Traversal of the above tree: 4-5-2-6-7-3-1

First Simple Tree


Let us create a simple tree with 4 nodes. The created tree would be as follows.
tree
----
1 <-- root
/ \
2 3
/
4
Binary Search Tree is a node-based binary tree data structure which has the
following properties:
 The left subtree of a node contains only nodes with keys lesser than the node’s
key.
 The right subtree of a node contains only nodes with keys greater than the node’s
key.
 The left and right subtree each must also be a binary search tree.
There must be no duplicate nodes.

The above properties of Binary Search Tree provides an ordering among keys so that
the operations like search, minimum and maximum can be done fast. If there is no
ordering, then we may have to compare every key to search for a given key.

Searching a key :
we want to search for the number, we start at the root, and then we compare the
value to be searched with the value of the root, if it’s equal we are done with the
search if it’s smaller we know that we need to go to the left subtree because in a
binary search tree all the elements in the left subtree are smaller and all the elements
in the right subtree are larger. Searching an element in the binary search tree is
basically this traversal, at each step we go either left or right and at each step we
discard one of the sub-trees.
we start with a search space of ‘n’ nodes and as we discard one of the sub-trees, we
discard ‘n/2’ nodes so our search space gets reduced to ‘n/2’. In the next step we
reduce the search space to ‘n/4’ and we repeat until we find the element or our
search space is reduced to only one node. The search here is also a binary search
hence the name; Binary Search Tree.

# A utility function to search a given key in BST


def search(root,key):
# Base Cases: root is null or key is present at root
if root is None or root.val == key:
return root
# Key is greater than root's key
if root.val < key:
return search(root.right,key)
# Key is smaller than root's key
return search(root.left,key)

#Program to create ,insert and search an element in an BST

class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data

def insert(self, data):


# Compare the new value with the parent node
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
# findval method to compare the value with nodes
def search(self, val):
if val < self.data:
if self.left is None:
return str(val)+" Not Found"
return self.left.search(val)
elif val > self.data:
if self.right is None:
return str(val)+" Not Found"
return self.right.search(val)
else:
print(str(self.data) + ' is found')

# Print the tree


def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()

# Use the insert method to add nodes


root = Node(12)
root.insert(6)
root.insert(14)
root.insert(3)
root.insert(15)
root.insert(10)
root.PrintTree()
print(root.search(7))
print(root.search(14))
print(root.search(12))
print(root.search(10)

You might also like