Trees and Binary Trees

  TREES AND BINARY TREES Become Rich Force Others Stock

  Rob to be Poor Fraud Banks

  

The class notes are a compilation and edition from many sources. The instructor does not claim intellectual property or ownership of the lecture notes. NATURE VIEW OF A TREE leaves branch es root

  COMPUTER SCIENTIST’S VIEW branches leaves root nodes

  WHAT IS A TREE 

  A tree is a finite nonempty set of elements.

  

  It is an abstract model of a

  Computers”R”Us hierarchical structure.

  

  consists of nodes with a parent-child relation.

  

  Applications:

  Sales Manufacturing R&D Organization charts File systems Programming environments US

  International Laptops Desktops Europe Asia Canada TREE TERMINOLOGY Subtree: tree consisting of a

  Root: node without parent (A) node and its descendants Siblings: nodes share the same parent Internal node: node with at least one child (A, B, C, F) External node (leaf ): node without

  A children (E, I, J, K, G, H, D) Ancestors of a node: parent, grandparent, grand-grandparent, etc.

  Descendant of a node: child, D B C grandchild, grand-grandchild, etc. Depth of a node: number of ancestors Height of a tree: maximum depth of any node (3)

  E F G H Degree of a node: the number of its children Degree of a tree: the maximum number of its node.

  I J K

TREE PROPERTIES

  Property Value A

  Number of nodes Height Root Node

  C B Leaves Interior nodes Ancestors of H Descendants of B

  D E F Siblings of E Right subtree of A Degree of this tree

  G H

  I

TREE ADT

  

  We use positions to abstract nodes

  

  Generic methods:

   integer size () boolean isEmpty () objectIterator elements () positionIterator positions () 

  Accessor methods:

   position root () position parent (p) positionIterator children (p)

  Query methods:

  boolean isInternal (p) boolean isExternal (p) boolean isRoot (p)

  Update methods:

  swapElements (p, q) object replaceElement (p, o)

  Additional update methods may be defined by data structures implementing the Tree ADT

INTUITIVE REPRESENTATION OF TREE NODE

  List Representation

  ( A ( B ( E ( K, L ), F ), C ( G ), D ( H ( M ), I, J ) ) ) The root comes first, followed by a list of links to sub-trees Data Link 1 Link 2 … Link n

  How many link fields are needed in such a representation? TREES 

  Every tree node:  object – useful information

   children – pointers to its children

  Data Data   Data Data   Data   Data   Data   A TREE REPRESENTATION 

  A node is represented by

  

  an object storing 

  Element

  

  Parent node

  B 

  Sequence of children nodes  

  A D F B D A F

   

  C E LEFT CHILD, RIGHT SIBLING REPRESENTATION Data Left

  Child Right Sibling

  A B C D

  I H G F E J K L

TREE TRAVERSAL

   Two main methods:

   Pre order

   Post order

   Recursive definition

   Pre order:

  

  visit the root

  

  traverse in preorder the children (subtrees)

   Post order

  

  traverse in postorder the children (subtrees)

  

  visit the root

PREORDER TRAVERSAL

  

  A traversal visits the nodes of a

  Algorithm preOrder(v)

  tree in a systematic manner

  visit(v) 

  In a preorder traversal, a node is

  for each child w of v

  visited before its descendants

  preorder (w) 

  Application: print a structured document

1 Become Rich

  2

  5

  9

1. Motivations

  2. Methods

  3. Success Stories

  3

  6

  7

  8

  4

  1.1 Enjoy

  1.2 Help

  2.1 Get a CS

  2.2 Start a

  2.3 Acquired Life Poor Friends PhD Web Site by Google

POSTORDER TRAVERSAL

  

  In a postorder traversal, a node is

  Algorithm postOrder(v)

  visited after its descendants

  for each child w of v 

  Application: compute space used

  postOrder (w)

  by files in a directory and its

  visit(v)

  subdirectories

  9 cs16/

  8

  3

  7 todo.txt homeworks/ programs/

  1K

  4

  5

  6

  1

  2

h1c.doc h1nc.doc DDR.java Stocks.java Robot.java

h1c.doc h1nc.doc DDR.java Stocks.java Robot.java

  3K

  2K

  10K

  25K

  20K

  3K

  2K

  10K

  25K

  20K

BINARY TREE

  

  A binary tree is a tree with the Applications: following properties:

  arithmetic expressions Each internal node has at most two decision processes children (degree of two) searching The children of a node are an ordered pair

  A 

  We call the children of an internal node left child and right child

  B C 

  Alternative recursive definition: a binary tree is either a tree consisting of a single node, OR a tree whose root has an ordered pair

  D E F G of children, each of which is a binary tree

  H

  I

BINARYTREE ADT

   

  

The BinaryTree ADT Update methods may be

extends the Tree ADT, defined by data structures i.e., it inherits all the implementing the methods of the Tree ADT BinaryTree ADT

   Additional methods:

  

  position leftChild (p)

  

  position rightChild (p)

  

  position sibling (p)

  Examples of the Binary Tree Skewed Binary Tree Complete Binary Tree

  1 A

  A A B

  2 B

  B C C

  3 F G

  D E D H

4 I

  E

  5 DIFFERENCES BETWEEN A TREE AND A BINARY TREE 

  A B A B

  The subtrees of a binary tree are ordered; those of a tree are not ordered.

  • Are different when viewed as binary trees.
  • Are the same when viewed as trees.

DATA STRUCTURE FOR BINARY TREES

  

  A node is represented by an object storing

  Element Parent node Left child node Right child node B D A C E

       

  B A D C E 

ARITHMETIC EXPRESSION TREE

   Binary tree associated with an arithmetic expression

  

  internal nodes: operators

  

  external nodes: operands

    Example: arithmetic expression tree for the expression (2

  (a - 1) + (3  b))

  •  

  2 3 b

  • a

  1

DECISION TREE

   Binary tree associated with a decision process

  

  internal nodes: questions with yes/no answer

  

  external nodes: decisions

   Example: dining decision

  Want a fast meal? How about coffee? On expense account?

  Starbucks Spike’s Al Forno Café Paragon

  Yes No Yes No Yes No

  

Maximum Number of Nodes in a

Binary Tree i

  The maximum number of nodes on depth i of a binary tree is 2 , i>=0. k+1 The maximum nubmer of nodes in a binary tree of height k is

  2 -1 , k>=0.

  Prove by induction. k i k

  1 

  2

  2

  1    i

  

FULL BINARY TREE

   A full binary tree of a given height k has

  2 k+1 –1 nodes. LABELING NODES IN A FULL BINARY TREE

   Label the nodes 1 through

  2 k+1 – 1 .

   Label by levels from top to bottom.  Within a level, label from left to right.

  1

  2

  3

  4

  5

  6

  7

  8

  9

NODE NUMBER PROPERTIES

  9

  15

  14

  13

  12

  11

  10

   Parent of node i is node i / 2 , unless i = 1 . 

  Node 1 is the root and has no parent.

  7

  6

  5

  4

  3

  2

  1

  8

NODE NUMBER PROPERTIES

  1

  2

  3

  4

  6

  5

  7

  8

  9

  10

  11

  12

  13

  14

  15

   Left child of node i is node 2i , unless 2i > n , where n is the number of nodes.

   If 2i > n , node i has no left child.

NODE NUMBER PROPERTIES

  1

  2

  3

  4

  6

  5

  7

  8

  9

  10

  11

  12

  13

  14

  15

   Right child of node i is node 2i+1 , unless 2i+1 > n , where n is the number of nodes.

   If 2i+1 > n , node i has no right child.

  Complete Binary Trees

  A labeled binary tree containing the labels 1 to n with root 1, branches leading to nodes labeled 2 and 3, branches from these leading to 4, 5 and 6, 7, respectively, and so on. A binary tree with n nodes and level k is complete iff its nodes correspond to the nodes numbered from 1 to n in the full binary tree of level k.

  1

  1

  2

  3

  2

  3

  6

  7

  4

  5

  7

  4

  6

  5

  14

  13

  15

  12

  9

  10

  11

  8

  8

9 Complete binary tree

  Binary Tree Traversals Let l, R, and r stand for moving left, visiting the node, and moving right.

  

There are six possible combinations of traversal

  lRr, lrR, Rlr, Rrl, rRl, rlR

  Adopt convention that we traverse left before right, only 3 traversals remain

  lRr, lrR, Rlr inorder, postorder, preorder

INORDER TRAVERSAL

  

  In an inorder traversal a node is visited after its left subtree and before its right subtree

  Algorithm inOrder(v) if isInternal (v)

  inOrder (leftChild (v)) visit(v)

  if isInternal (v)

  inOrder (rightChild (v))

  3

  1

  2

  5

  6

  

7

  9

  8

  4 PRINT ARITHMETIC EXPRESSIONS Specialization of an inorder traversal print operand or operator when visiting node print “(“ before traversing left

   subtree print “)“ after traversing right subtree

  Algorithm inOrder (v) if isInternal (v){ print(“

  ( ’’) inOrder (leftChild ( v))} print(v.element ()) if isInternal (v){ inOrder (rightChild ( v)) print (“

  •  

  ) ’’)}

  • 2 a

  1 3 b ((2  (a - 1)) + (3

   b))

EVALUATE ARITHMETIC EXPRESSIONS

   recursive method returning the value of a subtree

   when visiting an internal node, combine the values of the subtrees Algorithm evalExpr(v) if isExternal (v) return v.element () else x  evalExpr(leftChild ( v)) y  evalExpr(rightChild ( v))   operator stored at v return x  y

  •  
    • 2

  5

  1

  3

  2 CREATIVITY:

  V PATHLENGTH( TREE ) =  DEPTH( V  ) 

  TREE Algorithm pathLength( v, n ) Input: a tree node v and an initial value n Output: the pathLength of the tree with root v Usage: pl = pathLength(root, 0); if isExternal (v) return n return

  (pathLength(leftChild (v), n + 1) + pathLength(rightChild (v), n + 1) + n) EULER TOUR TRAVERSAL Generic traversal of a binary tree Includes a special cases the preorder, postorder and inorder traversals Walk around the tree and visit each node three times: on the left (preorder) from below (inorder) on the right (postorder)

    • 2

  5

  1

  3

  2 L

  B R

  

EULER TOUR TRAVERSAL

  eulerTour(node v) { perform action for visiting node on the left; if v is internal then eulerTour(v->left);

perform action for visiting node from below;

if v is internal then eulerTour(v->right);

perform action for visiting node on the right;

}

  TREE

BINARY TREE

  

sebuah pengorganisasian secara hirarki

dari beberapa buah simpul, dimana masing-masing simpul tidak mempunyai anak lebih dari 2.

   Simpul yang berada di bawah sebuah simpul dinamakan anak dari simpul tersebut.

   Simpul yang berada di atas sebuah simpul dinamakan induk dari simpul tersebut.

BINARY TREE

ISTILAH DALAM TREE

  Term Definition Node Sebuah elemen dalam sebuah tree; berisi sebuah informasi Parent Node yang berada di atas node lain secara langsung; B adalah

  parent dari D dan E

  

Child Cabang langsung dari sebuah node; D dan E merupakan children

  dari B

  Root Node teratas yang tidak punya parent Sibling Sebuah node lain yang memiliki parent yang sama; Sibling dari

  B adalah C karena memiliki parent yang sama yaitu A

  Leaf Sebuah node yang tidak memiliki children. D, E, F, G, I adalah

  leaf. Leaf biasa disebut sebagai external node, sedangkan node selainnya disebut sebagai internal node. B, A, C, H adalah

  internal node Level Semua node yang memiliki jarak yang sama dari root.

  Alevel 0; B,Clevel 1; D,E,F,G,Hlevel 2; Ilevel 3

  Depth Jumlah level yang ada dalam tree

STRUKTUR BINARY TREE

   Masing-masing simpul dalam binary tree terdiri dari tiga bagian yaitu sebuah data dan dua buah pointer yang dinamakan pointer kiri dan kanan.

DEKLARASI TREE

  typedef char typeInfo; typedef struct Node tree; struct Node { typeInfo info; tree *kiri; /* cabang kiri */ tree *kanan; /* cabang kanan */

  };

PEMBENTUKAN TREE

   Dapat dilakukan dengan dua cara : rekursif dan non rekursif

   Perlu memperhatikan kapan suatu node akan dipasang sebagai node kiri dan kapan sebagai node kanan.

   Misalnya ditentukan, node yang berisi info yang nilainya “lebih besar” dari parent akan ditempatkan di sebelah

kanan dan yang “lebih kecil” di sebelah

kiri.

   Sebagai contoh jika kita memiliki informasi “HKACBLJ” maka pohon biner

PEMBENTUKAN TREE

PEMBENTUKAN TREE

  Langkah-langkah Pembentukan Binary Tree

  1. Siapkan node baru

  • alokasikan memory-nya
  • masukkan info-nya
  • set pointer kiri & kanan = NULL

  2. Sisipkan pada posisi yang tepat

  • penelusuran  utk menentukan posisi yang tepat; info yang nilainya lebih besar dari parent akan ditelusuri di sebelah kanan, yang lebih kecil dari parent akan ditelusuri di sebelah kiri
  • penempatan  info yang nilainya lebih dari parent akan ditempatkan di sebelah kanan, yang lebih kecil

METODE TRAVERSAL

   Salah satu operasi yang paling umum dilakukan terhadap sebuah tree adalah kunjungan (traversing)

   Sebuah kunjungan berawal dari root, mengunjungi

setiap node dalam tree tersebut tepat hanya sekali

   Mengunjungi artinya memproses data/info yang ada pada node ybs

   Kunjungan bisa dilakukan dengan 3 cara:

  1. Preorder

  2. Inorder

  3. Postorder 

  

Ketiga macam kunjungan tersebut bisa dilakukan

  PREORDER 

  Kunjungan preorder, juga disebut dengan depth first order, menggunakan urutan: Cetak isi simpul yang dikunjungi Kunjungi cabang kiri Kunjungi cabang kanan PREORDER void preorder(pohon ph) { if (ph != NULL) { printf("%c ", ph->info); preorder(ph->kiri); preorder(ph->kanan); }

  } PREORDER A

B C

D E F G

A B D E C F G

  INORDER 

  Kunjungan secara inorder, juga sering disebut dengan symmetric order, menggunakan urutan: 

  Kunjungi cabang kiri 

  Cetak isi simpul yang dikunjungi 

  Kunjungi cabang kanan INORDER void inorder(pohon ph) { if (ph != NULL) {

inorder(ph->kiri);

printf("%c ", ph->info); inorder(ph->kanan); }

  }

  INORDER A

B C

D E F G

D B E A F C G

  POSTORDER 

  Kunjungan secara postorder menggunakan urutan: 

  Kunjungi cabang kiri 

  Kunjungi cabang kanan 

  Cetak isi simpul yang dikunjungi POSTORDER void postorder(pohon ph) { if (ph != NULL) { postorder(ph->kiri); postorder(ph->kanan); printf("%c ", ph->info); }

  }

  POSTORDER A

B C

D E F G

D E B F G C A