Docsity

Implementing and Serializing General Trees with More than Two Children - Prof. David J. Ga, Study notes of Data Structures and Algorithms

Partial preview of the text

Download Implementing and Serializing General Trees with More than Two Children - Prof. David J. Ga and more Study notes Data Structures and Algorithms in PDF only on Docsity!

Data Structures and Algorithms^ CS245-2009S-09General Trees^ David GallesDepartment of Computer ScienceUniversity of San Francisco

09-0:^ Trees with^ >^

2 children

How can we implement trees with nodes that have

>^2

children?

09-2:^ Trees with^ >^

2 children Linked List of Children

09-3:^ Left Child / Right Sibling^ We can integrate the linked lists with the nodesthemselves:

09-6:^ General Trees – NumNodes int numnodes(Node tree) {int descendants = 0;Node tmp;if (tree == null)return 0;for (tmp = tree.leftchild(); tmp != null;tmp = tmp.rightsib())descendants = descendants + numnodes(tmp);return descendants + 1;}

  • 09-5: General Trees – NumNodes Returns the number of nodes in a tree Number of Nodes =
    • Number of Nodes =
  • 09-8: Tree Operations – Height Returns the height of the tree (Length of the path to the deepest leaf) + 1 Height =
    • Height =

09-9:^ General Trees – Height int height(Node tree) {if (tree == null)return 0;return MAX((1 + height(tree.leftchild())),height(tree.rightsib()));}

09-11:^ Serializing Binary Trees^ Print a tree to a file, saving structure information^ First Try: Print out nodes, in order that they wouldappear in a PREORDER traversal.^ Why doesn’t this work?

A B C D E^ F G ABDEGCF

09-12:^ Serializing Binary Trees^ Printing out nodes, in order that they would appearin a PREORDER traversal does not work, becausewe don’t know when we’ve hit a null pointer^ Store null pointers, too!

A B C D E^ F G ABD//EG///C/F//

09-14:^ Serializing Binary Trees^ Printing out nodes, in order that they would appearin a PREORDER traversal does not work, becausewe don’t know when we’ve hit a null pointer^ Store null pointers, too!^ A B^

C D FE G ABD///CEG///F//

09-15:^ Serializing Binary Trees^ Printing out nodes, in order that they would appearin a PREORDER traversal does not work, becausewe don’t know when we’ve hit a null pointer^ Store null pointers, too!^ ABDE//G///CF/H///

09-17:^ Serializing Binary Trees^ If we are searializing a full binary tree (each nodecontains exactly 0 or 2 children), we can store asingle extra bit for each node 0 for an internalnode, 1 for a leaf:^ A

C B D G^ FE ABCDEFG 0100111

09-18:^ Serializing Binary Trees^ If we are searializing a full binary tree (each nodecontains exactly 0 or 2 children), we can store asingle extra bit for each node 0 for an internalnode, 1 for a leaf:

A^ E B^ G C DF