(14) Trees

# (14) Trees - Reading CMSC 132 Object-Oriented Programming...

This preview shows pages 1–4. Sign up to view the full content.

CMSC 132: Object-Oriented Programming II Department of Computer Science University of Maryland, College Park 1 2 Reading Read Sections 8.1-8.4 in the Koffman text (Sections 6.1-6.4 in the second edition) Trees Trees are hierarchical data structures having a one- to-many relationship between elements A tree node or element: Contains data Contains links to any number of other nodes ( children ) Is referred to by (at most) one other ( parent ) node parent node children nodes 3 Tree terminology The root is the node that has no parent A leaf is a node that has no children Interior nodes are all the nodes that have children root node leaf nodes interior nodes 4

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Tree terminology, con't. Siblings are two nodes with the same parent Descendents are the children of a node, and their descendents A subtree is the portion of a tree that is a tree by itself, consisting of any node and all its descendents siblings subtree 5 Tree terminology, con't. Level is a measure of a node’s distance from the root Definition of level: If a node is the root of a tree, its level is 1 Otherwise the node’s level is 1 + its parent’s level The height (or depth) of a tree is the maximum level of any node in the tree 6 height is 4 Binary trees A binary tree is a tree with at most two children per node they're referred to as a node's left and right child, and indicate its left and right subtrees binary tree left child parent right child 7 Tree traversal Often we want to 1. Find all the nodes in a tree 2. Determine their relationship This can be done by 1. Traversing the tree nodes in a tree in a prescribed order 2. Processing the nodes as they are encountered This procedure is called tree traversal 8
Tree traversal The goal is to visit every node in a binary tree Approaches: Breadth first visits closer nodes first Depth first A preorder traversal visits a parent node before its children An inorder traversal visits in the order left child, parent, right child A postorder traversal visits children before their parent 9 Depth-first tree traversal methods Preorder 1. Visit or process a node (the node is visited before its subtrees) 2. Visit the left child 3. Visit the right child Inorder 1. Visit the left child 2. Visit or process a node (the node is visited between its subtrees)

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 9

(14) Trees - Reading CMSC 132 Object-Oriented Programming...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online