Recursive size
This commit is contained in:
		
							parent
							
								
									5b7efc9ef3
								
							
						
					
					
						commit
						9eeba598e7
					
				
					 3 changed files with 6 additions and 18 deletions
				
			
		|  | @ -5,10 +5,10 @@ | |||
| 
 | ||||
| int main(void) { | ||||
|   Tree tree = {NULL}; | ||||
|   printf("Tree size: %d\n", tree_size(&tree)); | ||||
|   printf("Tree size: %d\n", tree_size(tree.root)); | ||||
|   tree_insert(&tree, 1); | ||||
|   tree_insert(&tree, 2); | ||||
|   tree_insert(&tree, 3); | ||||
|   printf("Tree size: %d\n", tree_size(&tree)); | ||||
|   printf("Tree size: %d\n", tree_size(tree.root)); | ||||
|   return 0; | ||||
| } | ||||
|  |  | |||
							
								
								
									
										18
									
								
								src/tree.c
									
										
									
									
									
								
							
							
						
						
									
										18
									
								
								src/tree.c
									
										
									
									
									
								
							|  | @ -49,22 +49,10 @@ int tree_remove(Tree *tree, int data) { return 1; } | |||
| 
 | ||||
| int tree_clear(Tree *tree) { return 1; } | ||||
| 
 | ||||
| int tree_size(Tree *tree) { | ||||
|   if (tree->root == NULL) { | ||||
| int tree_size(Node *node) { | ||||
|   if (node == NULL) { | ||||
|     return 0; | ||||
|   } | ||||
| 
 | ||||
|   int size = 0; | ||||
|   Node *current = tree->root; | ||||
|   while (current != NULL) { | ||||
|     size++; | ||||
|     if (current->left != NULL) { | ||||
|       current = current->left; | ||||
|     } else if (current->right != NULL) { | ||||
|       current = current->right; | ||||
|     } else { | ||||
|       current = NULL; | ||||
|     } | ||||
|   } | ||||
|   return size; | ||||
|   return 1 + tree_size(node->left) + tree_size(node->right); | ||||
| } | ||||
|  |  | |||
|  | @ -19,4 +19,4 @@ typedef struct Tree Tree; | |||
| int tree_insert(Tree *tree, int data); | ||||
| int tree_remove(Tree *tree, int data); | ||||
| int tree_clear(Tree *tree); | ||||
| int tree_size(Tree *tree); | ||||
| int tree_size(Node *node); | ||||
|  |  | |||
		Loading…
	
	Add table
		Add a link
		
	
		Reference in a new issue
	
	 Imbus
						Imbus