You are on page 1of 52

Trees & Binary Trees

1
The Abstract Data Type Tree
 An ADT tree root node
internal
 Has one entry point, the root node
nodes
 Each other node is either a leaf or an
internal node
 An internal node has 1 or more
children, nodes that can be reached
directly from that internal node.
 The internal node is said to be the
parent of its child nodes

leaf nodes
2
Properties of Trees
 The only access point is the root
 All nodes, except the root, have one parent
 like the inheritance hierarchy in Java
 Traditionally trees drawn upside down
root

leaves
3
Properties of Trees and Nodes
root
 siblings: two nodes that have
the same parent edge
 edge: the link from one node to
another
 path length: the number of
edges that must be traversed siblings
to get from one node to another

path length from root to this


node is 3

4
More Properties of Trees
 depth: the path length from the root of the tree
to this node
 height of a node: The maximum distance (path
length) of any leaf from this node
 a leaf has a height of 0
 the height of a tree is the height of the root of that
tree
 descendants: any nodes that can be reached via
1 or more edges from this node
 ancestors: any nodes for which this node is a
descendant

5
Tree Visualization
A

B C D

E F G H I J

K L M

N O
6
Your Turn

 What is the depth of the node


that contains M on the previous
slide?
A. 0

B. 1

C. 2

D. 3
7
Breadth First - Depth First
 breadth first search: Any search algorithm that
considers neighbors of a vertex (node), that is,
outgoing edges (links) of the vertex's
predecessor in the search, before any outgoing
edges of the vertex
 depth first search: Any search algorithm that
considers outgoing edges (links to children) of a
vertex (node) before any of the vertex's (node)
siblings, that is, outgoing edges of the vertex's
predecessor in the search. Extremes are
searched first.
8
Breadth First Search of Tree

A G X Z

W Q P O U

K B Z
L

M R
9
Breadth First Search

C search level 0 first


Find Node with B

A G X Z

W Q P O U

K B Z
L

M R

10
Breadth First Search
Find Node with B search level 1 next
C

A G X Z

W Q P O U

K B Z
L

M R
11
Breadth First Search
Find Node with B search level 2 next
C

A G X Z

W Q P O U

K B Z
L

M R
12
Breadth First Search
Find Node with B search level 3 next
C

A G X Z

W Q P O U

K B Z
L

M R
13
Depth First Search

Find Node with B C

A G X Z

W Q P O U

K B Z
L

M R

14
BFS & DFS Implementations

 Breadth first search typically


implemented with a Queue
 Depth first search typically
implemented with recursion
 Which technique do I use?
 depends on the problem

15
Binary Trees
 There are many variations on trees but we will
focus on binary trees
 binary tree: each node has at most two children
 the possible children are usually referred to as the left
child and the right child

parent

left right
child child
16
Full Binary Tree

 Full binary tree: a binary tree in which each node


has exactly 2 or 0 children

17
Your Turn
 What is the maximum height of
a full binary tree with 11 nodes?
A. 1

B. 3

C. 5

D. 7

E. Not possible to construct a full


binary tree with 11 nodes.
18
Complete Binary Tree
 complete binary tree: a binary tree in which every
level, except possibly the deepest is completely
filled. At depth n, the height of the tree, all nodes
are as far left as possible

A. Where would the next node go


to maintain a complete tree?
19
Your Turn

 What is the height of a complete


binary tree that contains N nodes?
A. 1
B. logN

C. N1/2
D. N

E. NlogN

20
Perfect Binary Tree
 perfect binary tree: a binary tree with all leaf nodes
at the same depth. All internal nodes have exactly
two children.
 a perfect binary tree has the maximum number of
nodes for a given height
 a perfect binary tree has (2(h+1) - 1) nodes where h
is the height of the tree
 height = 0 -> 1 node
 height = 1 -> 3 nodes
 height = 2 -> 7 nodes
 height = 3 -> 15 nodes

21
Balanced binary tree
a a
b c b
d e f g c e
d f
h i j
A balanced binary g h
tree i j
An unbalanced binary
tree
 A binary tree is balanced if every level above the lowest is
“full” (contains 2h nodes)
 In most applications, a reasonably balanced binary tree is
desirable
22
Sorted binary trees
 A binary tree is sorted if every node in the tree is
larger than (or equal to) its left descendants, and
smaller than (or equal to) its right descendants
 Equal nodes can go either on the left or the right
(but it has to be consistent)
10

8 15

4 12 20

17
23
Binary search in a sorted array
 Look at array location (lo + hi)/2

Searching for 5
(0+6)/2 = 3
Using a binary
hi = 2;
(0 + 2)/2 = 1 lo = 2; search tree
(2+2)/2=2
7

3 13
0 1 2 3 4 5 6
2 3 5 7 11 13 17 2 5 11 17

24
Binary Tree Class
 class BinTree {
int key;
BinTree leftChild;
BinTree rightChild;

// Other methods…
}
 A constructor for a binary tree should have three
parameters, corresponding to the three fields

25
A Binary Tree (Node) class

public abstract class BinTree{


private int key;
private BinTree leftChild;
private BinTree rightChild;

public BinTree();
public BinTree(int key,BinTree left,BinTree right);
public int getKey();
public BinTree getLeftChild();
public BinTree getRightChild();
public void setKey(int key);
public void setLeftChild(BinTree left);
public void setRightChild(BinTree right);
}

26
Binary Tree Traversals
 Many algorithms require all nodes of a binary tree
be visited and the contents of each node processed
or examined.
 There are 4 traditional types of traversals
 preorder traversal: process the root, then process all sub
trees (left to right)
 in order traversal: process the left sub tree, process the
root, process the right sub tree
 post order traversal: process the left sub tree, process the
right sub tree, then process the root
 level order traversal: starting from the root of a tree,
process all nodes at the same depth from left to right,
then proceed to the nodes at the next depth.
27
Breadth First and Level order Traversal

 A level order traversal of a tree could be


used as a breadth first search
 Search all nodes in a level before going
down to the next level

28
Tree Traversals

C D

F G H J

K L

29
Your Turn
 What is a the result of a post order
traversal of the tree on the previous
slide?
A. F C G A K H L D J

B. F G C K L H J D A

C. A C F G D H K L J

D. A C D F G H J K L

E. L K J H G F D C A

30
Tree traversals
 A binary tree (BT) recursive definition: BT consists of a
root, a left subtree and a right subtree
 To traverse (or walk) the binary tree is to visit each
node in the binary tree exactly once
 Tree traversals are naturally recursive
 Since a binary tree has three “parts,” there are six
possible ways to traverse the binary tree:

 root, left, right (pre-order)


 root, right, left
 left, root, right (in-order)
 right, root, left
 left, right, root (post-order)  right, left, root

31
Tree traversals using “flags”
 The order in which the nodes are visited during a tree
traversal can be easily determined by imagining there
is a “flag” attached to each node, as follows:

preorder inorder postorder

 To traverse the tree, collect the flags:


A A A

B C B C B C

D E F G D E F G D E F G

ABDECFG DBEAFCG DEBFGCA


32
Results of Traversals
 To determine the results of a traversal on a given
tree draw a path around the tree.
 start on the left side of the root and trace around the tree.
The path should stay close to the tree.

12 pre order: process when


pass down left side of node
12 49 13 5 42
in order: process when pass
49 42 underneath node
13 49 5 12 42
13 post order: process when
5 pass up right side of node
13 5 49 42 12

33
Preorder traversal
 In preorder, the root is visited first
 Here’s a preorder traversal to print out all the
elements in the binary tree:

public void preorderPrint(BinTree bt) {


if (bt == null) return;
System.out.println(bt.key);
preorderPrint(bt.leftChild);
preorderPrint(bt.rightChild);
}

34
Inorder traversal
 In inorder, the root is visited in the middle
 Here’s an inorder traversal to print out all the
elements in the binary tree:

public void inorderPrint(BinTree bt) {


if (bt == null) return;
inorderPrint(bt.leftChild);
System.out.println(bt.key);
inorderPrint(bt.rightChild);
}

35
Postorder traversal
 In postorder, the root is visited last
 Here’s a postorder traversal to print out all the
elements in the binary tree:

public void postorderPrint(BinTree bt) {


if (bt == null) return;
postorderPrint(bt.leftChild);
postorderPrint(bt.rightChild);
System.out.println(bt.key);
}

36
Copying a binary tree
 In postorder, the root is visited last
 Here’s a postorder traversal to make a complete copy of
a given binary tree:

public static BinTree copyTree(BinTree bt) {


if (bt == null) return null;
BinTree left = copyTree(bt.leftChild);
BinTree right = copyTree(bt.rightChild);
return new BinTree(bt.key, left, right);
}

37
Other traversals
 The other traversals are the reverse of these
three standard ones
 That is, the right subtree is traversed before the left
subtree is traversed
 Reverse preorder: root, right subtree, left
subtree
 Reverse inorder: right subtree, root, left subtree
 Reverse postorder: right subtree, left subtree,
root

38
Binary Search Tree (BST)
 Stores keys in the nodes in a way so that searching,
insertion and deletion can be done efficiently.
Binary search tree property
 For every node X, all the keys in its left subtree are smaller than the
key value in X, and all the keys in its right subtree are larger than the
key value in X

39
BST

A binary search tree Not a binary search tree

40
BST
Two binary search trees representing
the same set:

 Average depth of a node is O(log N); maximum


depth of a node is O(N)
41
BST Implementation

class BST {
Comparable key;
BST leftChild;
BST rightChild;

// add methods…
}

42
Searching BST

 If we are searching for 15, then we are done.


 If we are searching for a key < 15, then we
should search in the left subtree.
 If we are searching for a key > 15, then we
should search in the right subtree.

43
Searching for 9 …

44
Searching (find) Implementation
 Find X: return a reference to the node that has key X,
or NULL if there is no such node

public BST find(Comparable key, BST bst) {


if (bst == NULL) return NULL;
else if (key.compareTo(bst.key)==-1) return find(key,
bst.leftchild);
else if (key.compareTo(bst.key)==1) return find(key,bst.
rightchild);
else return bst;
}
 Time complexity
 O(height of the tree)
45
Inorder traversal of BST
 Print out all the keys in sorted order

Printing BST
keys using
inorder
traversal

Inorder: 2, 3, 4, 6, 7, 9, 13, 15, 17, 18, 20


46
findMin/ findMax

 Return the node containing the smallest element in


the tree
 Start at the root and go left as long as there is a left
child. The stopping point is the smallest element
public BST findMin(BST bst) {
if (bst == NULL) return NULL;
if (bst.leftchild == NULL) retun bst;
return findMin(bst.leftchild);
}

 Similarly for findMax


 Time complexity = O(height of the tree)
47
insert
 Proceed down the tree as you would with a find
 If X is found, do nothing (or update something)
 Otherwise, insert X at the last spot on the path traversed

Insert key 13

 Time complexity = O(height of the tree)


48
delete

 When we delete a node, we need to consider


how we take care of the children of the
deleted node.
 This has to be done such that the property of the
search tree is maintained.

49
delete
Three cases:
(1) the node is a leaf
 Delete it immediately
(2) the node has one child
 Adjust a pointer from the parent to bypass that node

Deletion of a node (4) with one child

Before After

50
delete
(3) the node has 2 children
 replace the key of that node with the minimum element at its
right subtree
 delete the minimum element
 Has either no child or only right child because if it has a left child,
that left child would be smaller and would have been chosen. So
invoke case 1 or 2.
Deletion of a node (2) with two children

Before After

 Time complexity = O(height of the tree)


51
Exercises
1. Draw a BST where the average depth of a node is
O(log N) and maximum depth of a node is O(N)
respectively, where N is the number of keys. Use
own generated keys with N=14.
2. Write a BST class including the constructor
methods, getter(accessor) methods,
setter(mutator) methods and the BST ADT
operations: find, insert, delete, findMin, findMax
and replace.

52

You might also like