Tree Tree v A tree is a collection

  • Slides: 12
Download presentation
Tree

Tree

Tree v A tree is a collection of nodes and edges v A tree

Tree v A tree is a collection of nodes and edges v A tree has only one root v Trees are hierarchical: Parent-child relationship between two nodes v basic operations of a tree: • tree traversals • insert node • delete node • searching

Level 0 1 2 E A A root Child (of root) R S T

Level 0 1 2 E A A root Child (of root) R S T E Leaves or terminal nodes M 3 Depth of T: 2 Tree height: 4 P L E

Binary Trees ´A tree in which no node can have more than two children

Binary Trees ´A tree in which no node can have more than two children

A General Tree & A Binary Tree

A General Tree & A Binary Tree

Balanced Binary Trees ´A binary tree is balanced if the heights of any node’s

Balanced Binary Trees ´A binary tree is balanced if the heights of any node’s two subtrees differ by no more than 1 ´Complete binary trees are balanced ´Full binary trees are complete and balanced ´B = HL - HR

Example: A A 1 -1=0 B Balance 2 -1=1 A A B C B

Example: A A 1 -1=0 B Balance 2 -1=1 A A B C B Balance D E Balance

Example of tree application: • Represent algebraic formulas Q: Write the following operations as

Example of tree application: • Represent algebraic formulas Q: Write the following operations as binary tree and determine the (tree Depth, tree height, number of levels). A. 2+3 + 2 3 1 Tree depth 2 Tree height 1 Number of levels

B. (6/2) * (20 -4) * - / 6 2 2 Tree depth 3

B. (6/2) * (20 -4) * - / 6 2 2 Tree depth 3 Tree height 2 Number of levels

Tree traversal Type of Traversal • Inorder traversal • Preorder traversal • Postorder traversal

Tree traversal Type of Traversal • Inorder traversal • Preorder traversal • Postorder traversal

´ Inorder traversal ´ Recursively print out all data in the left subtree ´

´ Inorder traversal ´ Recursively print out all data in the left subtree ´ Print the data at the root ´ Recursively print out all data in the right subtree ´ Pre-order traversal ´ Print the data at the root ´ Recursively print out all data in the left subtree ´ Recursively print out all data in the right subtree ´ Postorder traversal ´ Recursively print out all data in the left subtree ´ Recursively print out all data in the right subtree ´ Print the data at the root

Traverse the following binary tree using the three types of tree traversal 6 a.

Traverse the following binary tree using the three types of tree traversal 6 a. Preorder (NLR) 6, 2, 1, 4, 3, 7, 10 , 9, 11 7 2 b. Postorder (LRN) 1, 3, 4, 2, 9, 11 , 10, 7, 6 c. Inorder (LNR) 1 10 4 1, 2, 3, 4, 6, 7, 9, 10, 11 3 9 11