You are on page 1of 54

General Tree Concepts Binary Trees

Data Structures and Algorithms

Outline

Tree Data Structure


Examples Definition Terminology Definitions Examples Tree Traversal

Binary Tree

Binary Search Trees

Definition

Linear Lists and Trees

Linear lists (arrays, linked list)are useful for serially ordered data

(e1,e2,e3,,en) Days of week Months in a year Students in a class Khalids descendants Corporate structure Government Subdivisions Software structure

Trees are useful for hierarchically ordered data


Examples of trees

directory structure family trees:

all descendants of a particular person all ancestors born after year 1800 of a particular person

evolutionary tress (also called phylogenetic trees) albegraic expressions

Khalids Descendants

What are other examples of hierarchically ordered data?

Property of a Tree

A tree t is a finite nonempty set of nodes One of these elements is called the root Each node is connected by an edge to some other node A tree is a connected graph

There is a path to every node in the tree It can be proved that a tree has one less edge than the number of nodes.

There are no cycles in the tree.

Usually depicted with the root at the top

Is it a Tree?

NO!

yes!

All the nodes are not connected

yes! (but not


a binary tree)

NO!
There is a cycle and an extra edge (5 nodes and 5 edges)

yes! (its actually


the same graph as the blue one) but usually we draw tree by its levels

Subtrees

Tree Terminology

The element at the top of the hierarchy is the root. Elements next in the hierarchy are the children of the root. Elements next in the hierarchy are the grandchildren of the root, and so on. Elements at the lowest level of the hierarchy are the leaves.

Other Definitions

Leaves, Parent, Grandparent, Siblings, Ancestors, Descendents


Leaves = {Hassan,Gafar,Sami,Mohmmed}
Parent(Musa) = Khalid

Grandparent(Sami) = Musa
Siblings(Musa) = {Ahmed,Omer} Ancestors(Hassan) = {Amed,Khalid} Descendents(Musa)={Fahad,Sami}

10

Levels and Height

Root is at level 0 and its children are at level 1.

level 0 level 1

level 2 level 3

11

Degree of a node

Node degree is the number of children it has

12

Tree Degree

Tree degree is the maximum of node degrees

tree degree = 3

13

Measuring Trees

The height of a node v is the number of nodes on the longest path from v to a leaf

The height of the tree is the height of the root, which is the number of nodes on the longest path from the root to a leaf

The depth of a node v is the number of nodes on the path from the root to v

This is also referred to as the level of a node

Note that there are slightly different formulations of the height of a tree

Where the height of a tree is said to be the length (the number of edge) on the longest path from node to a leaf

Trees - Example
Level
0
root

Child (of root)

Leaves or terminal nodes

3 Depth of T: 2

Height of T: 1

Tree Terminology Example


A is the root node B is the parent of D and E C is the sibling of B D and E are the children of B D, E, F, G, I are external nodes, or leaves A, B, C, H are internal nodes The depth, level, or path length of E is 2 The height of the tree is 3 The degree of node B is 2

16

Tree Terminology Example

A path from A to D to G B subtree rooted at B E F C leaves: C,E,F,G G D

Tree Representation

Class TreeNode { Object element; TreeNode firstChild; TreeNode nextSibling; }

Binary Trees

A finite (possibly empty) collection of elements A nonempty binary tree has a root element and the remaining elements (if any) are partitioned into two binary trees They are called the left and right subtrees of the A binary tree
B left subtree of A C right child of A

G right subtree of C

19

Difference Between a Tree & a Binary Tree


A binary tree may be empty; a tree cannot be empty. No node in a binary tree may have a degree more than 2, whereas there is no limit on the degree of a node in a tree. The subtrees of a binary tree are ordered; those of a tree are not ordered. a b c c a b
- different when viewed as a binary tree - same when viewed as a tree

20

Binary Tree for Expressions

21

Height of a Complete Binary Tree


L0

L1 L2

L3

At each level the number of the nodes is doubled. total number of nodes: 1 + 2 + 22 + 23 = 24 - 1 = 15

Nodes and Levels in a Complete Binary Tree

Number of the nodes in a tree with M levels: 1 + 2 + 22 + . 2M = 2 (M+1) - 1 = 2*2M - 1 Let N be the number of the nodes. N = 2*2M - 1, 2*2M = N + 1 2M = (N+1)/2 M = log( (N+1)/2 ) N nodes : log( (N+1)/2 ) = O(log(N)) levels M levels: 2 (M+1) - 1 = O(2M ) nodes

Binary Tree Properties


1. The drawing of every binary tree with n elements, n > 0, has exactly n-1 edges.

2. A binary tree of height h, h >= 0, has at least h and at most 2h-1 elements in it.

24

Binary Tree Properties


3. The height of a binary tree that contains n elements, n >= 0, is at least (log2(n+1)) and at most n.

minimum number of elements maximum number of elements

25

Full Binary Tree


A full binary tree of height h has exactly 2h-1 nodes. Numbering the nodes in a full binary tree
Number the nodes 1 through 2h-1 Number by levels from top to bottom Within a level, number from left to right

26

Node Number Property of Full Binary Tree

Parent of node i is node (i/2), unless i = 1 Node 1 is the root and has no parent

27

Node Number Property of Full Binary Tree

Left child of node i is node 2i, unless 2i > n, where n is the total number of nodes. If 2i > n, node i has no left child.

28

Node Number Property of Full Binary Tree

Right child of node i is node 2i+1, unless 2i+1 > n, where n is the total number of nodes. If 2i+1 > n, node i has no right child.

29

Complete Binary Tree with N Nodes


Start with a full binary tree that has at least n nodes Number the nodes as described earlier. The binary tree defined by the nodes numbered 1 through n is the n-node complete binary tree. A full binary tree is a special case of a complete binary tree

30

Example of Complete Binary Tree

Complete binary tree with 10 nodes. Same node number properties (as in full binary tree) also hold here.

31

Binary Tree Representation


Array representation Linked representation

32

Array Representation of Binary Tree


The binary tree is represented in an array by storing each element at the array position corresponding to the number assigned to it.

33

Incomplete Binary Trees

Complete binary tree with some missing elements


34

Example Binary Tree

To find a nodes parent use this formula: Parents Index = (Childs Index 1) / 2

Array index from 0 Ex. To find nodes 2 left and right child Left Childs Index = 2 * Parents Index + 1 Right Childs Index = 2 * Parents Index + 2

35

Linked Representation of Binary Tree


The most popular way to present a binary tree Each element is represented by a node that has two link fields (leftChild and rightChild) plus an element field Each binary tree node is represented as an object whose data type is binaryTreeNode The space required by an n node binary tree is n * sizeof(binaryTreeNode)

36

Linked Representation of Binary Tree

37

Node Class For Linked Binary Tree


TreeNode class private class TreeNode { private String data; private TreeNode left; private TreeNode right; public TreeNode(String element) { data = element; left = null; right = null; } }

38

Common Binary Tree Operations


Determine the height Determine the number of nodes Make a copy Determine if two binary trees are identical Display the binary tree Delete a tree If it is an expression tree, evaluate the expression If it is an expression tree, obtain the parenthesized form of the expression

39

Binary Tree Traversal


A traversal of a tree is a systematic way of acces sing or "visiting" all the nodes in the tree. There are three basic traversal schemes: preord er, postorder, inorder .In any of these traversals we always visit the left subtree before the right

40

Binary Tree Traversal Methods

Preorder The root of the subtree is processed first before going into the left then right subtree (root, left, right). Inorder After the complete processing of the left subtree the root is processed followed by the processing of the complete right subtree (left, root, right). Postorder The root is processed only after the complete processing of the left and right subtree (left, right, root). Level order The tree is processed by levels. So first all nodes on level i are processed from left to right before the first node of level i+1 is visited

41

Preorder Traversal
public void preOrderPrint() { preOrderPrint(root); } private void preOrderPrint(TreeNode tree) { if (tree != null) { System.out.print(tree.data + " "); // Visit the root preOrderPrint(tree.left);// Traverse the left subtree preOrderPrint(tree.right); // Traverse the right subtree } }

42

Preorder Example (visit = print) N-L-R


H D L

43

Preorder of Expression Tree

/ * + a b - c d + e f Gives prefix form of expression.


44

Inorder Traversal
public void inOrderPrint() { inOrderPrint(root); } public void inOrderPrint(TreeNode t) { if (t != null) { inOrderPrint(t.left); System.out.print(t.data + " "); inOrderPrint(t.right); } }

45

Inorder Example (visit = print)


H D L

A A B

C C D

E E F

G G H

I I J

K K L

M M N

O O

L-N-R
46

Inorder by Projection

47

Inorder of Expression Tree

Gives infix form of expression, which is how we normally write math expressions. What about parentheses?

48

Postorder Traversal
public void ostOrderPrint() {

postOrderPrint(root);
} public void postOrderPrint(TreeNode t)

{
if (t != null) { postOrderPrint(t.left); postOrderPrint(t.right); System.out.print(t.data + " "); } }

49

Postorder Example (visit = print)


H D

L-R-N
L

C A C B E

G F D I

K K J M O

M N L

O H

50

Postorder of Expression Tree

a b + c d - * e f + / Gives postfix form of expression.


51

Level Order Example (visit = print)

Add and delete nodes from a queue Output: a b c d e f g h i j

52

Space and Time Complexity


The space complexity of each of the four traversal algorithm is O(n) The time complexity of each of the four traversal algorithm is O(n)

53

Summary

Tree, Binary Tree In order to process the elements of a tree, we consider accessing the elements in certain order Tree traversal is a tree operation that involves "visiting (or" processin g") all the nodes in a tree. Types of traversing Pre-order: Visit node first, pre-order all its subtrees from leftmost t o rightmost. Inorder: Inorder the node in left subtree and then visit the root follo wing by inorder traversal of all its right subtrees. Post-order: Post-order the node in left subtree and then post-order the right subtrees followed by visit to the node.

54

You might also like