Presentation is loading. Please wait.

Presentation is loading. Please wait.

Trees and Tree Traversals

Similar presentations


Presentation on theme: "Trees and Tree Traversals"— Presentation transcript:

1 Trees and Tree Traversals
CSC212 Data Structure Lecture 13 Trees and Tree Traversals Instructor: Prof. George Wolberg Department of Computer Science City College of New York

2 Motivation Linear structures Nonlinear Structures Why??? arrays
dynamic arrays linked lists Nonlinear Structures trees - Hierarchical Structures Graphs Why???

3 Application: Mailing Addresses
George Wolberg, CS Dept, CCNY, New York, NY 10031, USA 6 billion = 6,000,000,000 people in the world What kind of structure is the best for a postman to locate me? Array ? Linked list ? Tree ?

4 A Tree for all the mailing addresses
Earth China USA Korea MA NY Albany NYC CCNY CS G. Wolberg

5 Trees and Binary Trees Chapter 10 introduces trees.
This presentation illustrates basic terminology for binary trees and focuses on Complete Binary Trees: the simplest kind of trees Binary Tree Traversals: any kind of binary trees This lecture is an introduction to trees, illustrating basic terminology for binary trees, and focusing on complete binary Before this lecture, students should have a good understanding of the simpler linear data structures of lists, stacks, and queues. Data Structures and Other Objects Using C++

6 Binary Trees A binary tree has nodes, similar to nodes in a linked list structure. Data of one sort or another may be stored at each node. But it is the connections between the nodes which characterize a binary tree. In many ways, a tree is like the other structures you have seen: A tree consists of nodes, and each node can contain data of one sort or another.

7 Binary Trees A binary tree has nodes, similar to nodes in a linked list structure. Data of one sort or another may be stored at each node. But it is the connections between the nodes which characterize a binary tree. But, unlike a linked list, the connections between the nodes are more than a simple one-to-another progression. An example can illustrate the connections in a binary tree. An example can illustrate how the connections work

8 A Binary Tree of States Washington In this example, the data contained at each node is one of the 50 states. Arkansas Colorado Florida Arizona Oklahoma This is an example of a binary tree with nine nodes. Presumably each node contains information about one of the 50 states. In this example, the states are not arranged in any particular order, except insofar as I need to illustrate the different special kinds of nodes and connections in a binary tree. Mass. Hampshire New Nebraska

9 A Binary Tree of States Each tree has a special node called its root, usually drawn at the top. The first special kind of node is the root. Computer scientists always draw this special node at the top. (I think they must have flunked botany.)

10 A Binary Tree of States Each tree has a special node called its root, usually drawn at the top. The example tree has Washington as its root. In this example, Washington State is at the root. An interesting true story about Washington State: When Washington first applied for statehood, congress was considering several possible names for the new state, including Columbia since the major river in the state is the Columbia river. But congress was worried that people might get Columbia mixed up with the District of Columbia...so they decided to call it Washington instead.

11 A Binary Tree of States Each node is permitted to have two links to other nodes, called the left child and the right child. Each node in a binary tree is permitted to have two links downward to other nodes, called the left child and the right child.

12 A Binary Tree of States Each node is permitted to have two links to other nodes, called the left child and the right child. The fact that we allow two links to children is the reason that these trees are called binary trees. "Binary" means "two parts". Later you will see more general trees where the number of children is not restricted to two.

13 A Binary Tree of States Children are usually drawn below a node.
The right child of Washington is Colorado. The left child of Washington is Arkansas. But for binary trees, each node has at most two children. For example, the left child of Washington is Arkansas. The right child of Washington is Colorado.

14 A Binary Tree of States Some nodes have only one child. Arkansas has a
left child, but no right child. In a binary tree, a node might have a left child, but no right child. For example, the left child of Arkansas is Florida. But Arkansas has no right child.

15 A Quiz Which node has only a right child?
Some nodes have only one child. Which node has only a right child? Here is a quiz: Find a node that has a right child, but no left child...

16 A Quiz Some nodes have only one child. Florida has only a right child.
In this example, Massachusetts is the right child of Florida, and Florida has no left child.

17 A Binary Tree of States A node with no children is called a leaf.
Some nodes have no children, and those nodes are called leaves. In this example, there are four leaves: Massachusetts, Oklahoma, New Hampshire (or is that Vermont?) and Nebraska. (Yes, that really is Nebraska. Either the author ran out of room on the slide and had to shrink it, or the author is from rival state Colorado.)

18 A Binary Tree of States Each node is called the parent of its children. Washington is the parent of Arkansas and Colorado. We can also refer to the parent of a node, which is the upward link. For example, Washington is the parent of both Arkansas and Colorado.

19 A Binary Tree of States Two rules about parents:
The root has no parent. Every other node has exactly one parent. There are two rules about parents in any tree: 1. The root never has a parent. 2. Every other node has exactly one parent. There is also a related rule which is not written here, but is part of the definition of a tree: If you start at the root, there is always one way to get from the root to any particular node by following a sequence of downward links (from a parent to its child).

20 A Binary Tree of States Two nodes with the same parent are called siblings. Arkansas and Colorado are siblings. Two nodes that have the same parent are called siblings, as shown here. In a binary tree, a node has at most one sibling.

21 Complete Binary Trees A complete binary tree is a special kind of binary tree which will be useful to us. The rest of this lecture demonstrates a special kind of binary tree called a complete binary tree. The tree has several applications, and is also special because it is extremely easy to implement.

22 Complete Binary Trees A complete binary tree is a special kind of binary tree which will be useful to us. When a complete binary tree is built, its nodes are generally added one at a time. As with any tree, the first node must be the root. When a complete binary tree is built, its first node must be the root.

23 Complete Binary Trees The second node of a complete binary tree is always the left child of the root... With a complete binary tree, the second node must be the left child of the root.

24 Complete Binary Trees The second node of a complete binary tree is always the left child of the root... ... and the third node is always the right child of the root. The next node must be the right child of the root.

25 Complete Binary Trees The next nodes must always fill the next level from left to right. And so we continue, adding nodes. But in a complete binary tree, the way that we add nodes is restricted: Nodes must completely fill each level from left-to-right before proceeding to the next level. Following this rule, where would the fifth node have to be placed?

26 Complete Binary Trees The next nodes must always fill the next level from left to right. The fifth node must go in the next available spot in this level, which is the right child of Arkansas. By the way, there is also an interesting story about Idaho. Apparently congress decreed that the border between Idaho and Montana was to be the continental divide. So the surveyers started at Yellowstone Park, mapping out the border, but at “Lost Trail Pass” they made a mistake and took a false divide. They continued along the false divide for several hundred miles until they crossed over a ridge and saw the Clark Fork River cutting right across what they thought was the divide. At this point, they just gave up and took the rest of the border straight north to Canada. So those of you who come from Kalispell and Missoula Montana should really be Idahonians.

27 Complete Binary Trees The next nodes must always fill the next level from left to right. Then we can add the left child of Colorado...

28 Complete Binary Trees The next nodes must always fill the next level from left to right. ...and the right child of Colorado. Where would the next node after this go?...

29 Complete Binary Trees The next nodes must always fill the next level from left to right. ...now we can move to the next level, and add the first node as the left child of Florida.

30 Complete Binary Trees The next nodes must always fill the next level from left to right. Then the right child of Florida.

31 Is This Complete? Just to check your understanding, is this binary tree a complete binary tree? No, it isn't since the nodes of the bottom level have not been added from left to right.

32 Is This Complete? Is this complete?
No, since the third level was not completed before starting the fourth level.

33 Is This Complete? This is also not complete since Washington has a right child but no left child.

34 Is This Complete? But this binary tree is complete. It has only one node, the root.

35 Is This Complete? Yes! It is called the empty tree, and it has no nodes, not even a root. This binary tree is also complete, although you might have to squint to see it. You see, this binary tree has no nodes at all. It is called the empty tree, and it is considered to be a complete binary tree.

36 Full Binary Trees A full binary tree is a special kind of complete binary tree FULL When a full binary tree is built, its nodes are generally added one at a time. As with any tree, the first node must be the root. When a full binary tree is built, its first node must be the root.

37 Full Binary Trees The second node of a full binary tree is always the left child of the root... not FULL yet With a complete binary tree, the second node must be the left child of the root.

38 Full Binary Trees The second node of a full binary tree is always the left child of the root... ... and you MUST have the third node which always the right child of the root. FULL The next node must be the right child of the root.

39 Full Binary Trees The next nodes must always fill the next level from left to right. And so we continue, adding nodes. But in a full binary tree, the way that we add nodes is restricted: Nodes must completely fill each level from left-to-right before proceeding to the next level. Following this rule, where would the fifth node have to be placed? not FULL yet

40 Full Binary Trees The next nodes must always fill the next level from left to right. The fifth node must go in the next available spot in this level, which is the right child of Arkansas. By the way, there is also an interesting story about Idaho. Apparently congress decreed that the border between Idaho and Montana was to be the continental divide. So the surveyers started at Yellowstone Park, mapping out the border, but at “Lost Trail Pass” they made a mistake and took a false divide. They continued along the false divide for several hundred miles until they crossed over a ridge and saw the Clark Fork River cutting right across what they thought was the divide. At this point, they just gave up and took the rest of the border straight north to Canada. So those of you who come from Kalispell and Missoula Montana should really be Idahonians. not FULL yet

41 Full Binary Trees The next nodes must always fill the next level from left to right. Then we can add the left child of Colorado... not FULL yet

42 Full Binary Trees The next nodes must always fill the next level from left to right...until every leaf has the same depth (2) ...and the right child of Colorado. Where would the next node after this go?... FULL!

43 Full Binary Trees The next nodes must always fill the next level from left to right. ...now we can move to the next level, and add the first node as the left child of Florida.

44 Full Binary Trees The next nodes must always fill the next level from left to right. Then the right child of Florida.

45 Is This Full? Just to check your understanding, is this binary tree a complete binary tree? No, it isn't since the nodes of the bottom level have not been added from left to right.

46 Is This Full? Just to check your understanding, is this binary tree a complete binary tree? No, it isn't since every non-leaf node should have two children

47 Is This Full? Yes.

48 Is This Full? This binary tree is also complete. It has only one node, the root.

49 Is This Full? Yes! It is called the empty tree, and it has no nodes, not even a root. This binary tree is also complete, although you might have to squint to see it. You see, this binary tree has no nodes at all. It is called the empty tree, and it is considered to be a complete binary tree.

50 Implementing a Complete Binary Tree
We will store the data from the nodes in a partially-filled array. An integer to keep track of how many nodes are in the tree 3 There is one last feature of complete binary trees that you need to learn: How to implement a complete binary tree using a partially-filled array. With this implementation, the data from each node is placed in one component of a partially-filled array. The primary thing we need to keep track of is where in the array does each node belong? An array of data We don't care what's in this part of the array.

51 Implementing a Complete Binary Tree Using an Array
We will store the date from the nodes in a partially-filled array. An integer to keep track of how many nodes are in the tree 3 The solution to this problem is in Section 10.2 of the text, which discusses several different ways to implement binary trees. The simplest implementation uses a partially-filled array, as suggested by this picture, but you should be warned: The array implementation is only practical for complete binary trees. Read Section 10.2 to see details of how the entries are stored. An array of data We don't care what's in this part of the array.

52 Implementing a Complete Binary Tree Using an Array
Root is at component [0] Parent of node in [i] is at [(i-1)/2) Children (if exist) of node [i] is at [2i+1] and [2i+2] Total node number …+2d-1+r, r <= 2d, d is the depth

53 Binary Tree Summary Binary trees contain nodes.
Each node may have a left child and a right child. If you start from any node and move upward, you will eventually reach the root. Every node except the root has one parent. The root has no parent. Complete binary trees require the nodes to fill in each level from left-to-right before starting the next level. A quick summary . . .

54 Binary Tree Basics A binary tree is a structure in which:
Each node can have at most two children, and in which a unique path exists from the root to every other node. The two children of a node are called the left child and the right child, if they exist.

55 A Binary Tree Exercise V Q L E T A K S

56 How many leaf nodes? V Q L T E A K S

57 How many descendants of Q?
V Q L T E A K S

58 How many ancestors of K? V Q L T E A K S
Question: How to implement a general binary tree ?

59 Implementing a Binary Tree with a Class for Nodes
Root V Q L T E A K S

60 Binary Tree Nodes Each node of a binary tree is stored in an object of a new binary_tree_node class that we are going to define Each node contains data as well as pointers to its children (nodes) An entire tree is represented as a pointer to the root node

61 binary_tree_node Class
bintree variables functions //retrievals data left right //set set_data set_left set_right //boolean is_leaf template <class Item> class binary_tree_node { public: ...... private: Item data_field; binary_tree_node *left_field; binary_tree_node *right_field; };

62 Creating and Manipulating Trees
Consider only two functions Clearing a tree Return nodes of a tree to the heap Copying a tree The Implementation is easier than it seems if we use recursive thinking

63 Clearing a Tree Root V Q L T E A K S Clear LEFT SUBTREE

64 Clearing a Tree Root V L A S Clear RIGHT SUBTREE

65 Clearing a Tree Root V Return root node to the heap

66 Clearing a Tree Root NULL Set the root pointer to NULL

67 Clear a Tree key: recursive thinking bintree
template <class Item> void tree_clear(binary_tree_node<Item>*& root_ptr) // Library facilities used: cstdlib { if (root_ptr != NULL) tree_clear( root_ptr->left( ) ); // clear left sub_tree tree_clear( root_ptr->right( ) ); // clear right sub_tree delete root_ptr; // return root node to the heap root_ptr = NULL; // set root pointer to the null }

68 Copy a Tree Can you implement the copy? (p 467) bintree
template <class Item> binary_tree_node<Item>* tree_copy(const binary_tree_node<Item>* root_ptr) // Library facilities used: cstdlib { binary_tree_node<Item> *l_ptr; binary_tree_node<Item> *r_ptr; if (root_ptr == NULL) return NULL; else l_ptr = tree_copy( root_ptr->left( ) ); // copy the left sub_tree r_ptr = tree_copy( root_ptr->right( ) ); // copy the right sub_tree return new binary_tree_node<Item>( root_ptr->data( ), l_ptr, r_ptr); } // copy the root node and set the the root pointer }

69 Binary Tree Traversals
bintree pre-order traversal root (left sub_tree) (right sub_tree) in-order traversal (left sub_tree) root (right sub_tree) post-order traversal (left sub_tree) (right sub_tree) root backward in-order traversal (right sub_tree) root (left sub_tree)

70 Preorder Traversal: J E A H T M Y
Print first tree ‘J’ ‘E’ ‘T’ ‘A’ ‘H’ ‘M’ ‘Y’ Print left subtree second Print right subtree last

71 Preorder Traversal Example: print the contents of each node
template <class Item> void preorder_print(const binary_tree_node<Item>* node_ptr) // Library facilities used: cstdlib, iostream { if (node_ptr != NULL) std::cout << node_ptr->data( ) << std::endl; preorder_print(node_ptr->left( )); preorder_print(node_ptr->right( )); }

72 Inorder Traversal: A E H J M T Y
Print second tree ‘J’ ‘E’ ‘T’ ‘A’ ‘H’ ‘M’ ‘Y’ Print left subtree first Print right subtree last

73 Inorder Traversal Example: print the contents of each node
template <class Item> void inorder_print(const binary_tree_node<Item>* node_ptr) // Library facilities used: cstdlib, iostream { if (node_ptr != NULL) inorder_print(node_ptr->left( )); std::cout << node_ptr->data( ) << std::endl; inorder_print(node_ptr->right( )); }

74 Postorder Traversal: A H E M Y T J
Print last tree ‘J’ ‘E’ ‘T’ ‘A’ ‘H’ ‘M’ ‘Y’ Print left subtree first Print right subtree second

75 Postorder Traversal Example: print the contents of each node
template <class Item> void postorder_print(const binary_tree_node<Item>* node_ptr) // Library facilities used: cstdlib, iostream { if (node_ptr != NULL) postorder_print(node_ptr->left( )); postorder_print(node_ptr->right( )); std::cout << node_ptr->data( ) << std::endl; }

76 Backward Inorder Traversal: Y T M J H E A
Print second tree ‘J’ ‘E’ ‘T’ ‘A’ ‘H’ ‘M’ ‘Y’ Print left subtree last Print right subtree first

77 Backward Inorder Traversal: Y T M J H E A
tree Print right subtree first Print second Print left subtree last

78 A Useful Backward Inorder Traversal
bintree Indent each number according its depth template <class Item, class SizeType> void print(binary_tree_node<Item>* node_ptr, SizeType depth) // Library facilities used: iomanip, iostream, stdlib { if (node_ptr != NULL) print(node_ptr->right( ), depth+1); std::cout << std::setw(4*depth) << ""; // Indent 4*depth spaces. std::cout << node_ptr->data( ) << std::endl; print(node_ptr->left( ), depth+1); }

79 A Challenging Question:
For the traversals we have seen, the “processing” was simply printing the values of the node But we’d like to do any kind of processing We can replace “cout” with some other form of “processing” But how about 1000 kinds? Can template be helpful? Solution::::::::> (pages 501 – 507)

80 A parameter can be a function
write one function capable of doing anything A parameter to a function may be a function. Such a parameter is declared by the name of the function’s return type (or void), then the name of the parameter (i.e. the function), and finally a pair of parentheses (). Inside () is a list of parameter types of that parameter function Example int sum ( void f (int&, double), int i,...);

81 Preorder Traversal – print only
Example: print the contents of each node template <class Item> void preorder_print(const binary_tree_node<Item>* node_ptr) // Library facilities used: cstdlib, iostream { if (node_ptr != NULL) std::cout << node_ptr->data( ) << std::endl; preorder_print(node_ptr->left( )); preorder_print(node_ptr->right( )); }

82 Preorder Traversal – general form
A template function for tree traversals template <class Item> void preorder(void f(Item&), binary_tree_node<Item>* node_ptr) // Library facilities used: cstdlib { if (node_ptr != NULL) f( node_ptr->data( ) ); // node_ptr->data() return reference ! preorder(f, node_ptr->left( )); preorder(f, node_ptr->right( )); }

83 Preorder Traversal – how to use
Define a real function before calling void printout(int & it) // Library facilities used: iostream { std::cout << it << std::endl; } Can you print out all the node of a tree pointed by root ? binary_tree_node<int> *root; .... preorder(printout, root); Yes!!!

84 Preorder Traversal – another functions
Can define other functions... void assign_default(int& it) // Library facilities used: iostream { it = 0; } // unfortunately template does not work here for function parameters You can assign a default value to all the node of a tree pointed by root: binary_tree_node<int> *root; .... preorder(assign_default, root);

85 Preorder Traversal – how to use
Can the function-arguments be template? template <class Item> void printout(Item& it) // Library facilities used: iostream { std::cout << it << std::endl; } Can you print out all the node of a tree pointed by root ? binary_tree_node<string> *root; .... preorder(print_out, root); X ! print_out should have real types

86 Preorder Traversal – how to use
The function-arguments may be template if... template <class Item> void printout(Item& it) // Library facilities used: iostream { std::cout << it << std::endl; } Can you print out all the node of a tree pointed by root ? binary_tree_node<string> *root; .... preorder(print_out<string>, root); But you may do the instantiation like this

87 Preorder Traversal – a more general form
bintree An extremely general implementation (p 505) template <class Process, class BTNode> void preorder(Process f, BTNode* node_ptr) // Note: BTNode may be a binary_tree_node or a const binary tree node. // Process is the type of a function f that may be called with a single // Item argument (using the Item type from the node), // as determined by the actual f in the following. // Library facilities used: cstdlib { if (node_ptr != NULL) f( node_ptr->data( ) ); preorder(f, node_ptr->left( )); preorder(f, node_ptr->right( )); }

88 Functions as Parameters
We can define a template function X with functions as parameters – which are called function parameters A function parameter can be simply written as Process f ( where Process is a template), and the forms and number of parameters for f are determined by the actual call of f inside the template function X The real function argument for f when calling the the template function X cannot be a template function, it must be instantiated in advance or right in the function call

89 Summary Tree, Binary Tree, Complete Binary Tree
child, parent, sibling, root, leaf, ancestor,... Array Representation for Complete Binary Tree Difficult if not complete binary tree A Class of binary_tree_node each node with two link fields Tree Traversals recursive thinking makes things much easier A general Tree Traversal A Function as a parameter of another function

90 Copyright from slide 2 – slide 49:
Presentation copyright 1997 Addison Wesley Longman, For use with Data Structures and Other Objects Using C++ by Michael Main and Walter Savitch. Some artwork in the presentation is used with permission from Presentation Task Force (copyright New Vision Technologies Inc) and Corel Gallery Clipart Catalog (copyright Corel Corporation, 3G Graphics Inc, Archive Arts, Cartesia Software, Image Club Graphics Inc, One Mile Up Inc, TechPool Studios, Totem Graphics Inc). Students and instructors who use Data Structures and Other Objects Using C++ are welcome to use this presentation however they see fit, so long as this copyright notice remains intact. Feel free to send your ideas to: Michael Main THE END


Download ppt "Trees and Tree Traversals"

Similar presentations


Ads by Google