tree简化max和min代码实现,并且添加递归宏定义

This commit is contained in:
建峰 2025-04-27 23:55:41 +08:00
parent 4530508a1b
commit bad8d68180

View File

@ -12,6 +12,8 @@
#include "queue.h" #include "queue.h"
#include "stack.h" #include "stack.h"
#define TREE_RECURSIVE_ENABLED
static struct _tree_node* tree_node_new(struct _tree* self, void* obj) static struct _tree_node* tree_node_new(struct _tree* self, void* obj)
{ {
assert(self != NULL); assert(self != NULL);
@ -57,7 +59,7 @@ static void tree_node_free(struct _tree_node** node)
static uint32_t tree_height_node(struct _tree* self, struct _tree_node* root) static uint32_t tree_height_node(struct _tree* self, struct _tree_node* root)
{ {
#if 0 #ifdef TREE_RECURSIVE_ENABLED
assert(self != NULL); assert(self != NULL);
if (root == NULL) if (root == NULL)
{ {
@ -242,7 +244,7 @@ static struct _tree_node* tree_turn_right_then_left(struct _tree* self, struct _
*/ */
static bool tree_avl_rebalance(struct _tree* self, struct _tree_node* root) static bool tree_avl_rebalance(struct _tree* self, struct _tree_node* root)
{ {
#if 0 #ifdef TREE_RECURSIVE_ENABLED
assert(self != NULL); assert(self != NULL);
if (root == NULL) if (root == NULL)
{ {
@ -253,7 +255,6 @@ static bool tree_avl_rebalance(struct _tree* self, struct _tree_node* root)
return false; return false;
} }
// self->print_obj(root->obj);
tree_set_balance(self, root); tree_set_balance(self, root);
int balance = root->balance; int balance = root->balance;
if (balance == 2) if (balance == 2)
@ -288,6 +289,7 @@ static bool tree_avl_rebalance(struct _tree* self, struct _tree_node* root)
self->_root = root; self->_root = root;
} }
return true; return true;
#else #else
assert(self != NULL); assert(self != NULL);
if (root == NULL) if (root == NULL)
@ -365,59 +367,28 @@ static struct _tree_node* tree_find(struct _tree* self, void* obj)
static struct _tree_node* tree_find_min(struct _tree* self, struct _tree_node* root) static struct _tree_node* tree_find_min(struct _tree* self, struct _tree_node* root)
{ {
assert(self != NULL); assert(self != NULL);
#if 0
if (root == NULL)
{
return NULL;
}
if (root->left == NULL)
{
return root;
}
return tree_find_min(self, root->left);
#else
while (root != NULL) while (root != NULL)
{ {
if (root->left != NULL) if (root->left == NULL)
{ {
break;
}
root = root->left; root = root->left;
} }
else
{
return root; return root;
}
}
return root;
#endif
} }
static struct _tree_node* tree_find_max(struct _tree* self, struct _tree_node* root) static struct _tree_node* tree_find_max(struct _tree* self, struct _tree_node* root)
{ {
#if 0
assert(self != NULL);
if (root == NULL)
{
return NULL;
}
if (root->right == NULL)
{
return root;
}
return tree_find_max(self, root->right);
#else
while (root != NULL) while (root != NULL)
{ {
if (root->right != NULL) if (root->right == NULL)
{ {
break;
}
root = root->right; root = root->right;
} }
else
{
return root; return root;
}
}
return root;
#endif
} }
/** /**