This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: 1 1 Trees Binary Trees 6A 2 Trees 3 Binary Trees A binary tree is either empty or it contains a root node and left and rightsubtrees that are also binary trees. A binary tree is a nonlinear data structure. The top node of a tree is called the root . Any node in a binary tree has at most 2 children . Any node in a binary tree has exactly one parent node (except the root). 4 Tree Terminology A G F E D C B root parent leftchild rightchild leaf leftsubtree rightsubtree 5 Types of Binary Trees Expression Trees * +  / 2 5 6 3 7 (6 / 2 + 5) * (7  3) 6 Types of Binary Trees Huffman Trees C D x B x y y A z 1 1 1 A 45% B 30% C 20% D 5% A 1 B 00 C 010 D 011 1001010100 = ABACAB 2 7 Types of Binary Trees Binary Search Trees 84 41 96 24 37 50 13 98 8 More Terminology A full binary tree is a binary tree such that  all leaves have the same level, and  every nonleaf node has 2 children. A complete binary tree is a binary tree such that  every level of the tree has the maximum number of nodes possible except possibly the deepest level, and  at the deepest level, the nodes are as far left as possible. 9 Examples A G F E D C B A E D C B FULL (and COMPLETE) COMPLETE 10 Binary Trees & Recursion Consider two nodes in a tree, X and Y. X is an ancestor of Y if X is the parent of Y, or X is the ancestor of the parent of Y. It’s RECURSIVE! X is a descendant of Y if X is the child of Y, or X is the descendant of the child of Y. 11 Binary Trees Levels A G F E D C B Level 1 Level 2 Level 3 12 Binary Trees  Levels The level of a node Y is BASE CASE RECURSIVE CASE 1, if the Y is the root 1 + the level of the parent of Y, if Y is not the root 3 13 Binary Tree  Height The height of a binary tree T is the number of nodes in the longest path from the root node to a leaf node. BASE CASE RECURSIVE CASE 0, if T is empty if T is not empty, max(height(left(T)), height(right(T))) + 1 14 Binary Tree Traversals A G F C D E B PREORDER ABDECFG INORDER DBEAFCG POSTORDER DEBFGCA 15 Traversal Example A G E D C B preorder inorder postorder F H I ABDFGCEHI BFDGAEIHC FGDBIHECA 16 Traversals are Recursive Preorder traversal 1. Visit the root....
View
Full Document
 Spring '09
 ReidMiller
 Tree traversal

Click to edit the document details