From d7a05df2f4a48db3bdf3d4746f9c6c137186d0c9 Mon Sep 17 00:00:00 2001 From: wjf-hs Date: Tue, 25 Jun 2024 11:45:27 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=A9=E7=94=A8=E9=98=9F=E5=88=97=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0=E6=A0=91=E7=9A=84=E9=AB=98=E5=BA=A6=E8=AE=A1=E7=AE=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/tree.c | 53 ++++++++++++++++++++++++++++++----------------------- 1 file changed, 30 insertions(+), 23 deletions(-) diff --git a/src/tree.c b/src/tree.c index b74554d..c7b4664 100644 --- a/src/tree.c +++ b/src/tree.c @@ -1521,7 +1521,7 @@ static struct _tree_node* tree_trun_right_then_left(struct _tree* self, struct _ int32_t tree_height(struct _tree* self, struct _tree_node* root) { -#if 1 +#if 0 assert(self != NULL); if(root == NULL) { @@ -1536,34 +1536,40 @@ int32_t tree_height(struct _tree* self, struct _tree_node* root) { return 0; } - struct _tree_node *node = root; - int32_t left_height = 0, right_height = 0; - int32_t left_height_max = 0, right_height_max = 0; + int32_t height = 0; + int32_t count_cur_level = 0; + int32_t count_next_level = 0; - stack_t stack = stack_new(); - stack_init(stack, sizeof(struct _tree_node*)); - stack->push(stack, &root); - while(!stack->empty(stack)) + struct _tree_node* node = root; + queue_t queue = queue_new(); + queue_init(queue, sizeof(struct _tree_node*)); + + queue->push(queue, &node); + while(!queue->empty(queue)) { - stack->pop(stack, &node); - left_height = stack->size(stack); - if(left_height > left_height_max) - { - left_height_max = left_height; - } - - if(node->right != NULL) - { - stack->push(stack, &node->right); - } + queue->pop(queue, &node); if(node->left != NULL) { - stack->push(stack, &node->left); + queue->push(queue, &node->left); + } + if(node->right != NULL) + { + queue->push(queue, &node->right); + } + + if(count_cur_level == count_next_level) + { + count_next_level = queue->size(queue); + height++; + count_cur_level = 1; + } + else + { + count_cur_level++; } } - stack_free(stack); - - return left_height_max > right_height_max ? left_height_max : right_height_max; + queue_free(queue); + return height; #endif } @@ -2142,6 +2148,7 @@ void tree_avl_inorder(struct _tree* self, struct _tree_node* root) { stack->pop(stack, &node); self->print_obj(node->obj); + node = node->left; } }