Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
67 views

Trees (Binary Trees, 2-3 Trees, AVL Trees)

Trees (binary trees, 2-3 trees, AVL trees)
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

Trees (Binary Trees, 2-3 Trees, AVL Trees)

Trees (binary trees, 2-3 trees, AVL trees)
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

Trees (binary trees, 2-3 trees, AVL trees)

Tree
 Tree is a non-linear data structure which organizes
data in a hierarchical structure and this is a recursive
definition.

 OR
 A tree is a connected graph without any circuits.

 OR
 If in a graph, there is one and only one path between
every pair of vertices, then graph is called as a tree.

Tree
Tree Terminology
Root
 The first node from where the tree originates is called
as a root node. In any tree, there must be only one root
node. We can never have multiple root nodes in a tree
data structure.

 Here, node A is the only root node.


Edge
 The connecting link between any two nodes is called
as an edge.
 In a tree with n number of nodes, there are exactly (n-
1) number of edges.
Parent node
 The node which has a branch from it to any other node
is called as a parent node.
 In other words, the node which has one or more
children is called as a parent node.
 In a tree, a parent node can have any number of child
nodes.
•Node A is the parent of nodes B and C
•Node B is the parent of nodes D, E and F
•Node C is the parent of nodes G and H
•Node E is the parent of nodes I and J
•Node G is the parent of node K
Child node
 The node which is a descendant of some node is called
as a child node.
 All the nodes except root node are child nodes.

•Nodes B and C are the children of node A


•Nodes D, E and F are the children of node
B
•Nodes G and H are the children of node C
•Nodes I and J are the children of node E
•Node K is the child of node G
Siblings
 Nodes which belong to the same parent are called
as siblings.
 In other words, nodes with the same parent are sibling
nodes.

•Nodes B and C are siblings


•Nodes D, E and F are siblings
•Nodes G and H are siblings
•Nodes I and J are siblings
Degree
 Degree of a node is the total number of children of
that node.
 Degree of a tree is the highest degree of a node
among all the nodes in the tree.
•Degree of node A = 2
•Degree of node B = 3
•Degree of node C = 2
•Degree of node D = 0
•Degree of node E = 2
•Degree of node F = 0
•Degree of node G = 1
•Degree of node H = 0
•Degree of node I = 0
•Degree of node J = 0
•Degree of node K = 0
Internal node
 The node which has at least one child is called as
an internal node.
 Internal nodes are also called as non-terminal nodes.
 Every non-leaf node is an internal node.

Here, nodes A, B, C, E and G are internal nodes.


Leaf node
 The node which does not have any child is called as
a leaf node.
 Leaf nodes are also called as external
nodes or terminal nodes.

Here, nodes D, I, J, F, K and H are leaf nodes.


Level
 In a tree, each step from top to bottom is called
as level of a tree.
 The level count starts with 0 and increments by 1 at
each level or step.
Height
 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 a tree is the height of root node.
 Height of all leaf nodes = 0
•Height of node A = 3
•Height of node B = 2
•Height of node C = 2
•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
Depth
 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.
 Depth of the root node = 0
 The terms “level” and “depth” are used
•Depth of node A = 0
interchangeably. •Depth of node B = 1
•Depth of node C = 1
•Depth of node D = 2
•Depth of node E = 2
•Depth of node F = 2
•Depth of node G = 2
•Depth of node H = 2
•Depth of node I = 3
•Depth of node J = 3
•Depth of node K = 3
Subtree
 In a tree, each child from a node forms
a subtree recursively.
 Every child node forms a subtree on its parent node.
Forest
 A forest is a set of disjoint trees.
 Path :- The sequence of consecutive edges is called
path. In the tree shown in the above image, path to the
node E is A→ B → E.
 Ancestor node :- An ancestor of a node is any
predecessor node on a path from root to that node.
The root node doesn't have any ancestors. In the tree
shown in the above image, the node F have the
ancestors, B and A.
Types of Tree
General Tree
 General Tree stores the elements in a hierarchical
order in which the top level element is always present
at level 0 as the root element. All the nodes except the
root node are present at number of levels. The nodes
which are present on the same level are called siblings
while the nodes which are present on the different
levels exhibit the parent-child relationship among
them. A node may contain any number of sub-trees.
The tree in which each node contain 3 sub-tree, is
called ternary tree.
Forest
 Forest can be defined as the set of disjoint trees
obtained by deleting the root node and the edges
which connects root node to the first level node.
Expression trees
 Expression trees are used to evaluate the simple
arithmetic expressions. Expression tree is basically a
binary tree where internal nodes are represented by
operators while the leaf nodes are represented by
operands. Expression trees are widely used to solve
algebraic expressions like (a+b)*(a-b). Consider the
following example.

 Q. Construct an expression tree by using the


following algebraic expression.
 (a + b) / (a*b - c) + d
Expression trees
Tournament tree
 Tournament tree are used to record the winner of the match in each
round being played between two players. Tournament tree can also be
called as selection tree or winner tree. External nodes represent the
players among which a match is being played while the internal nodes
represent the winner of the match played. At the top most level, the
winner of the tournament is present as the root node of the tree.
 For example, tree .of a chess tournament being played among 4 players
is shown as follows. However, the winner in the left sub-tree will play
against the winner of right sub-tree.
 Binary Tree
 Binary tree is a data structure in which each node can
have at most 2 children. The node present at the top
most level is called the root node. A node with the 0
children is called leaf node. Binary Trees are used in the
applications like expression evaluation and many more.
We will discuss binary tree in detail, later in this tutorial.
 Binary Search Tree
 Binary search tree is an ordered binary tree. All the
elements in the left sub-tree are less than the root while
elements present in the right sub-tree are greater than or
equal to the root node element. Binary search trees are
used in most of the applications of computer science
domain like searching, sorting, etc.
Binary Tree
Binary Tree
Binary Tree
 Binary tree is a special tree data structure in which
each node can have at most 2 children. Thus, in a
binary tree, Each node has either 0 child or 1 child or 2
children.
Draw all binary trees with n unlabeled nodes
 Consider we want to draw all the binary trees possible
with 3 unlabeled nodes.
nC =𝑛! /
r
(𝑟!(𝑛−𝑟)!)

 Hence, binary trees possible with 3 unlabeled nodes


 = 2 x 3C3 / (3 + 1)
 = 6C3 / 4 = 20/4
=5
Draw all binary trees with n labeled nodes

 Q: Draw all binary trees possible with 3 labeled nodes.


 Using the above formula, we have-
 x
 Number of binary trees possible with 3 labeled nodes
 = { 2 x 3C3 / (3 + 1) } x 3!
 = { 6C3 / 4 } x 6
 =5x6
 = 30
Draw all binary trees with n labeled nodes

 Every other unlabeled structure gives rise to 6 different


labeled structures.
 Thus, in total (5x6 = 30) different labeled binary trees
are possible.
Types of Binary Trees
Rooted binary tree
 A rooted binary tree is a binary tree that satisfies the
following 2 properties-
 It has a root node.
 Each node has at most 2 children.
Full binary
 A binary tree in which every node has either 0 or 2
children is called as a Full binary tree.
 Full binary tree is also called as Strictly binary tree.
Complete binary tree
 A complete binary tree is a binary tree that satisfies
the following 2 properties-
 Every internal node has exactly 2 children.
 All the leaf nodes are at the same level.
Almost complete binary tree
 An almost complete binary tree is a binary tree that
satisfies the following 2 properties-
 All the levels are completely filled except possibly the
last level.
 The last level must be strictly filled from left to right.
Skewed binary tree
 A skewed binary tree is a binary tree that satisfies
the following 2 properties-
 All the nodes except one node has one and only one
child.
 The remaining node has no child.
 OR
 A skewed binary tree is a binary tree of n nodes such
that its depth is (n-1).
Traversals of Binary Trees

 Often want iterate over and process nodes of a tree


 Can walk the tree and visit the nodes in order
 This process is called tree traversal
 Three kinds of binary tree traversal:
 Preorder
 Inorder
 Postorder
 According to order of subtree root w.r.t. its children

Chapter 8: Trees 40
Binary Tree Traversals
 Preorder: Visit root, traverse left, traverse right
 Inorder: Traverse left, visit root, traverse right
 Postorder: Traverse left, traverse right, visit root

41
Visualizing Tree Traversals

Preorder ?
Preorder: a, b, d, g, e, h, c, f, i, j
Inorder ?
Inorder: d, g, b, h, e, a, i, f, j, c
Postorder ?
Postorder: g, d, h, e, b, i, j, f, c, a
Traversals of Expression Trees
 Inorder traversal can insert parentheses where they belong
for infix form
 Postorder traversal results in postfix form
 Prefix traversal results in prefix form

Infix form : (x+y) * ((a+b)/c)

Postfix form: x y + a b + c / *

Prefix form: * + x y / + a b c
Traversing Trees
 Preorder: Root, then Children
 +A*B/CD
 Postorder: Children, then Root +
 ABCD/*+
 Inorder: Left child, Root, Right child A *
 A+B*C/D

B /

C D

45
Arithmetic Expression Using BT
+ inorder traversal
A/B*C*D+E
infix expression
* E
preorder traversal
+**/ABCDE
* D prefix expression
postorder traversal
AB/C*D*E+
/ C
postfix expression
level order traversal
A B +*E*D/CAB
2-3 Trees
 Each internal node has either 2 or 3 children
 All leaves are at the same level
 2-3 tree is a tree, in which every internal node (non-
leaf) has either one data element and two children or
two data elements and three children.
 If a node contains one data element leftVal, it has two
subtrees (children) namely left and middle. Whereas if
a node contains two data elements leftVal and
rightVal, it has three subtrees namely left, middle and
right.
2-3 Trees with Ordered Nodes
2-node 3-node

• leaf node can be either a 2-node or a 3-node

CSCI 3110 49
Example of 2-3 Tree

CSCI 3110 50
2-3 Tree insertion Algo
 In a two-three tree, the algorithm will be as follows:
 If the tree is empty, create a node and put value into
the node.
 Otherwise find the leaf node where the value belongs.
 If the leaf node has only one value, put the new value
into the node.
 If the leaf node has more than two values, split the
node and promote the median of the three values to
parent.
 If the parent then has three values, continue to split
and promote, forming a new root node if necessary
Inserting Items
Insert 38

CSCI 3110 52
Inserting Items
Insert 38

divide leaf
insert in leaf and move middle result
value up to parent

CSCI 3110 53
Inserting Items
Insert 37

CSCI 3110 54
Inserting Items
Insert 36

divide leaf
insert in leaf and move middle
value up to parent

overcrowded
node

CSCI 3110 55
Inserting Items
... still inserting 36

divide overcrowded node,


move middle value up to parent, result
attach children to smallest and largest

CSCI 3110 56
Inserting Items
After Insertion of 35, 34, 33

CSCI 3110 57
3 cases of insertion
 Insertion: There are 3 possible cases in insertion
which have been discussed below:
 Case 1: Insert in a node with only one data element
3 cases of insertion
 Case 2: Insert in a node with two data elements whose
parent contains only one data element.

 Case 3: Insert in a node with two data elements whose


parent also contains two data elements.
Search in 2-3 Tree
Inventor: Adelson, Velski & Landis
AVL trees
 AVL trees are special kind of binary search trees.
 Balance Factor : differences between heights of left &
right subtrees for every node is less than or equal to 1.
 Also called as self-balancing binary search trees.

is AVL because differences between not AVL because difference between


heights of left and right subtrees for heights of left & right subtrees for 8
every node is less than or equal to 1. and 18 is greater than 1.
AVL Trees

This tree is an AVL tree because:


1. It is a binary search tree.
2. The difference between height
of left subtree and right subtree of
every node is at most one.

This tree is not an AVL tree because-


•The difference between height of left
subtree and right subtree of root node = 4
– 2 = 2.
•This difference is greater than one.
AVL Rotations
 BalanceFactor = height(right-sutree) − height(left-
sutree)
 If the difference in the height of left and right sub-
trees is more than 1, the tree is balanced using some
rotation techniques.
 AVL Rotations
 To balance itself, an AVL tree may perform the following
four kinds of rotations −
 Left rotation
 Right rotation
 Left-Right rotation
 Right-Left rotation
Left Rotation
 If a tree becomes unbalanced, when a node is inserted
into the right subtree of the right subtree, then we
perform a single left rotation:

 node A has become unbalanced as a node is inserted


in the right subtree of A's right subtree. We perform
the left rotation by making A the left-subtree of B.
Right Rotation
 AVL tree may become unbalanced, if a node is inserted
in the left subtree of the left subtree. The tree then
needs a right rotation.
-

-
Left-Right Rotation
State Action

A node has been inserted into the right subtree of the left
subtree. This makes C an unbalanced node. These
scenarios cause AVL tree to perform left-right rotation.

We first perform the left rotation on the left subtree of C.


This makes A, the left subtree of B.

Node C is still unbalanced, however now, it is because of


the left-subtree of the left-subtree.

We shall now right-rotate the tree, making B the new root


node of this subtree. C now becomes the right subtree of
its own left subtree.

The tree is now balanced.


Right-Left Rotation
State Action

A node has been inserted into the left subtree of the right
subtree. This makes A, an unbalanced node with balance
factor 2.

First, we perform the right rotation along C node,


making C the right subtree of its own left subtree B.
Now, B becomes the right subtree of A.

Node A is still unbalanced because of the right subtree of


its right subtree and requires a left rotation.

A left rotation is performed by making B the new root node


of the subtree. A becomes the left subtree of its right
subtree B.

The tree is now balanced.


AVL Tree Example:
• Insert 14, 17, 11, 7, 53, 4, 13 into an empty AVL tree

14

11 17

7 53

4
AVL Tree Example:
• Insert 14, 17, 11, 7, 53, 4, 13 into an empty AVL tree

14

7 17

4 11 53

13
AVL Tree Example:
• Now insert 12

14

7 17

4 11 53

13

12
AVL Tree Example:
• Now insert 12

14

7 17

4 11 53

12

13
AVL Tree Example:
• Now the AVL tree is balanced.

14

7 17

4 12 53

11 13
AVL Tree Example:
• Now insert 8

14

7 17

4 12 53

11 13

8
AVL Tree Example:
• Now insert 8

14

7 17

4 11 53

8 12

13
AVL Tree Example:
• Now the AVL tree is balanced.

14

11 17

7 12 53

4 8 13
AVL Tree Example:
• Now remove 53

14

11 17

7 12 53

4 8 13
AVL Tree Example:
• Now remove 53, unbalanced

14

11 17

7 12

4 8 13
AVL Tree Example:
• Balanced! Remove 11

11

7 14

4 8 12 17

13
AVL Tree Example:
• Remove 11, replace it with the largest in its left branch

7 14

4 12 17

13
AVL Tree Example:
• Remove 8, unbalanced

4 14

12 17

13
Binary Tree Representation
 A tree is represented by a pointer to the topmost node
in tree. If the tree is empty, then value of root is NULL.
A Tree node contains following parts.
1. Data
2. Pointer to left child
3. Pointer to right child
 Below is example of a tree node with an integer data.
class Node {
int key;
Node left, right;
public Node(int item) {
key = item;
left = right = null;
}
}
Ex01 – in memory trees
class Node {
int key;
Node left, right;
public Node(int item) {
key = item; In memory Tree:
left = right = null;
} 1
} / \
public class BinaryTree { 2 3
// Root of Binary Tree
/ \ / \
Node root;
// Constructors 4 null null null
BinaryTree(int key) { / \
root = new Node(key); null null
}
BinaryTree() {
root = null;
}
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
}
}
Ex01b – Very Simple BT
class BinarySearchTreeSimple {
class Node {
int key;
Node left, right;
public Node(int item) {
key = item;
left = right = null;
}
}
Node root; // Root of BST
BinarySearchTreeSimple() {// Constructor
root = null;
}
// This method mainly calls insertRec()
void insert(int key) {
root = insertRec(root, key);
}

Node insertRec(Node root, int key) {/* recursive function to insert new key in BST */
if (root == null) {/* If the tree is empty, return a new node */
root = new Node(key);
return root;
}
if (key < root.key) /* Otherwise, recur down the tree */
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);
/* return the (unchanged) node pointer */
return root;
}
Ex01b – Very Simple BT
// This method mainly calls InorderRec()
void inorder() {
inorderRec(root);
}
// A utility function to do inorder traversal of BST
void inorderRec(Node root) {
if (root != null) {
inorderRec(root.left);
System.out.println(root.key);
inorderRec(root.right);
}
}
// Driver Program to test above functions
public static void main(String[] args) {
BinarySearchTreeSimple tree = new BinarySearchTreeSimple();
/* Let us create following BST
50
/ \
30 70 output:
/ \ / \
20 40 60 80 */
20
tree.insert(50); 30
tree.insert(30);
tree.insert(20);
40
tree.insert(40); 50
tree.insert(70);
tree.insert(60);
60
tree.insert(80); 70
// print inorder traversal of the BST
tree.inorder();
80
}
}
Lab exercises
 Provided Practice code for lab:
 BinaryTree.java – simple in memory nodes of trees.
 BinarySearchTreeSimple.java – A bit simpler code
 BinarySearchTree.java – complete program
 BinarySearchTreeInteractive.java – out of scope of this
course as code is complex, but still check it out, run
compile and capture screen shots of operations.
Lab 12 task:
 Compile and Run BinarySearchTreeInteractive.java
 Capture screen shots of operations and submit it to google forms before 11:55 PM
today.

You might also like