42
Binary Trees

Binary Trees. DCS – SWC 2 Binary Trees Sets and Maps in Java are also available in tree-based implementations A Tree is – in this context – a data structure

Embed Size (px)

Citation preview

Binary Trees

DCS – SWC 2

Binary Trees

• Sets and Maps in Java are also available in tree-based implementations

• A Tree is – in this context – a data structure which allows fast O(log(n)) insertion, deletion and lookup of elements

• Furthermore, a Tree maintains an ordering of the elements

DCS – SWC 3

Binary Trees

• A Tree can be perceived as a generali-sation of a Linked List:

DCS – SWC 4

Binary Trees

• A Tree consists of nodes, which contain data, and references to (up to) n other nodes– n = 1: Linked List– n = 2: Binary Tree

• If node A refers to node B, we say that– Node A is the parent of node B– Node B is a child of node A

DCS – SWC 5

Binary Trees

• The node at the top of the tree is called the root node, and does not have a parent

• The nodes at the edge of the tree are called leaves, and do not have any children

Root

Leaf

Leaf

DCS – SWC 6

Binary Trees

• For a node A, we call the set of nodes consisting of the children of A, and the children of the children of A, and so forth, the descendants of A

Descendants of 5

DCS – SWC 7

Binary Search Trees

• A Binary Tree is thus a special type of Tree, where each node has (up to) 2 children

• A Binary Search Tree has some additio-nal properties– The data in each node must be of the type Comparable (i.e. implement the interface)

– The nodes must obey certain ordering rules

DCS – SWC 8

Binary Search Trees

• Ordering rules for nodes in a binary search tree:– The data values of all descendants to the left

of any node are less than the data value stored in that node

– The data values of all descendants to the right of any node are larger than the data value stored in that node

– No duplicates allowed

DCS – SWC 9

Binary Search Trees

All these nodes are smaller than 10

All these nodes are larger than 10

DCS – SWC 10

Binary Search Trees

• Searching in a Binary Search Tree is quite fast: O(log(n))

• How do we check if a value v is found in the tree?

1. Set current node N = root node

2. If value(N.data) = v, we are done, else• If value(N.data) < v, set N = left child (stop if null)• If value(N.data) > v, set N = right child (stop if null)

3. Go to 2

DCS – SWC 11

Binary Search Trees

public class BinarySearchTree

{

private Node root;

private class Node {...}

public BinarySearchTree() {root = null; }

public boolean contains(Comparable data) {...}

public void add(Comparable data) {...}

public void delete(Comparable data) {...}

}

DCS – SWC 12

Binary Search Trees

// NOTE: Inner class, public instance fields OK

private class Node

{

public Comparable data;

public Node left;

public Node right;

public Node(Comparable data) {...}

public boolean contains(Comparable data) {...}

public void add(Comparable data) {...}

public void delete(Comparable data) {...}

}

DCS – SWC 13

Binary Search Trees// BinarySearchTree implementations

public boolean contains(Comparable data)

{

if (root == null) return false;

else return root.contains();

}

public void add(Comparable data)

{

if (root == null) root = new Node(data);

else root.add(data);

}

public void delete(Comparable data)

{

...

}

DCS – SWC 14

Binary Search Treespublic boolean contains(Comparable v)

{

if (data.compareTo(v) == 0)

return true;

Node next;

if (data.compareTo(v) < 0)

next = left;

else

next = right;

if (next == null)

return false;

else

return (next.contains());

}

DCS – SWC 15

Binary Search Trees

• We can search a Binary Search Tree in O(log(n)), which is fast

• However, the condition for this ability is that the tree is always ”sorted”, i.e. obeys the ordering rules

• Adding or deleting an element must preserve this ordering!

DCS – SWC 16

Binary Search Trees

• Adding a new element E with value v is done using a recursive algorithm

1. Set current node N = root node

2. If N = null, replace it with E, else

3. If value(N.data) = v, we are done, else• If value(N.data) < v, set N = left child• If value(N.data) > v, set N = right child

4. Go to 2

DCS – SWC 17

Binary Search Treespublic void add(Comparable v)

{

if (data.compareTo(v) < 0)

{

if (left == null)

left = new Node(v);

else

left.add(v);

}

else if (data.compareTo(v) > 0)

{

if (right == null)

right = new Node(v);

else

right.add(v);

}

}

DCS – SWC 18

Binary Search Trees

• Deletion is actually the hardest part

• What happens to the children of some deleted node N?

• We must handle the cases where N has 0, 1 or 2 children

• 0 children: Easy. Just find N and delete it. Parent reference (if any) to N must be set to null

DCS – SWC 19

Binary Search Trees

N

Before After

DCS – SWC 20

Binary Search Trees

• 1 child: – Fairly easy. Find N and delete it. Parent refe-

rence to N must be rerouted to the child of N– Note that if N is the root node, then the child

of N becomes the new root node!

DCS – SWC 21

Binary Search Trees

N

Before After

C

C

Note that C may have children itself…

DCS – SWC 22

Binary Search Trees

• 2 children: – Complicated… Idea is to move the node with

the next larger value in the tree up to take the position of N

– Next larger value is found as the leftmost node in the right subtree of N

– Keep going left in that subtree, until a node with no left child is found. Call this node L

– Replace N with L

DCS – SWC 23

Binary Search Trees

• Replace N with L– Copy data from L into N (not links!)– Delete original L, following the procedure for

deleting a node with zero or a single child (L cannot have a left child)

• These operations will preserve the ordering properties of the tree

DCS – SWC 24

Tree Traversal

• The fact that a Binary Search Tree is ordered, make certain tasks quite easy

• For instance, printing out the content of the tree in sorted order

DCS – SWC 25

Tree Traversal

• Printing out a tree in sorted order:– Print out the left subtree– Print out data in the root node– Print out the right subtree

• Again, a highly recursive algorithm…

DCS – SWC 26

Tree Traversal

public void printNodes() // Node class

{

if (left != null)

left.printNodes();

System.out.print(data + ” ”);

if (right != null)

right.printNodes();

}

DCS – SWC 27

Tree Traversal

// BinarySearchTree class

public void printTree()

{

if (root != null)

root.printNodes();

}

DCS – SWC 28

Tree Traversal

1

2

3

4

5

7

86

DCS – SWC 29

Tree Traversal

• This is known as in-order tree traversal:– Apply operation to left subtree– Apply basic operation to root– Apply operation to right subtree

DCS – SWC 30

Tree Traversal

• We also have pre-order tree traversal:– Apply basic operation to root– Apply operation to left subtree– Apply operation to right subtree

DCS – SWC 31

Tree Traversal

1

2

3 4

5

7 8

6

DCS – SWC 32

Tree Traversal

• And finally post-order tree traversal:– Apply operation to left subtree– Apply operation to right subtree– Apply basic operation to root

DCS – SWC 33

Tree Traversal

1

2

3

4

5

7

8

6

DCS – SWC 34

Tree Traversal

• What tree traversal method to use depends entirely on your application

• In-order outputs the content of the tree in sorted order

• Pre- and post-order do not, but are used for other types of algorithms

DCS – SWC 35

Choosing a proper container

• We have now learned about many types of containers for data

• Which one is best…?

• It depends…– Usage scenarios– Data types

DCS – SWC 36

Choosing a proper container

• Issues in choosing a proper container– How do you access the elements?– Does element order matter?– Which operations must be fast?– Choosing between hash tables and trees

(when using sets and maps)– Should I supply a comparator (when using

trees)?

DCS – SWC 37

Choosing a proper container

• How do you access the elements?– If you need access by a key, you should use a

map– If you need access by an index, you should

use an array or array list– If you only need to check if an element is

already present in your container, you can use a set

DCS – SWC 38

Choosing a proper container

• Does element order matter?– If elements should remain sorted, use a

TreeSet– If the order of insertion should be preserved,

use a linked list, array or array list– If it does not matter, let other criteria decide

your choice

DCS – SWC 39

Choosing a proper container

• Which operations must be fast?– Add and remove at the end of the container,

use a linked list– Looking up a value quickly, use a set or map– If it does not matter, let other criteria decide

your choice

DCS – SWC 40

Choosing a proper container

• Choosing between hash tables and trees (when using sets and maps)

• If your elements/keys are strings, use a hash table• If your elements/keys are defined by yourself,

define proper hashCode and equals methods and use hash tables

• If your elements/keys are defined by someone else, use hash tables if the hashCode and equals methods are properly defined, otherwise use trees

DCS – SWC 41

Choosing a proper container

• Should I supply a comparator (when using trees)?– If the data type in your tree implements the Comparable interface properly, then no need for further action

– If not, you can still use a tree anyway, by supplying a class that implements the Comparator interface, that can compare objects of the type used in the tree

DCS – SWC 42

Exercises

• Review: R16.15

• Programming: P16.17, P16.18

• Tip: When implementing a Binary Search Tree class, only implement the methods you actually need. For instance, you pro-bably don’t need the remove method…