AVL树的插入(暂无删除)

#include <stdio.h>
#include <stdlib.h>

#define max(x, y)       (((x) > (y)) ? (x) : (y))

typedef struct node
{
  int           id;
  int           h; // height
  struct node   *left;
  struct node   *right;
} node;

static node *findmin(node *root)
{
  if (root == NULL)
    return (NULL);

  if (root->left == NULL)
    return (root);
  else
    return (findmin(root->left));
}

static int height(node *root)
{
  if (root == NULL)
    return (-1);
  else
    return root->h;
}

static node *single_rotate_right(node *k2)
{
  node  *k1 = k2->left;

  k2->left = k1->right;
  k1->right = k2;

  k2->h = max(height(k2->left), height(k2->right)) + 1;
  k1->h = max(height(k1->left), height(k1->right)) + 1;

  return (k1);
}

static node *single_rotate_left(node *k2)
{
  node  *k1 = k2->right;

  k2->right = k1->left;
  k1->left = k2;

  k2->h = max(height(k2->left), height(k2->right)) + 1;
  k1->h = max(height(k1->left), height(k1->right)) + 1;

  return (k1);
}

static node *right_left(node *k3)
{
  k3->right = single_rotate_right(k3->right);
  return (single_rotate_left(k3));
}

static node *left_right(node *k3)
{
  k3->left = single_rotate_left(k3->left);
  return (single_rotate_right(k3));
}

node *insert(int id, node *root)
{
  if (root == NULL)
  {
    root = malloc(sizeof(node));
    if (root == NULL)
    {
      printf("out of memory\n");
      return (NULL);
    }
    root->id = id;
    root->h = 0;
    root->left = root->right = NULL;
  }
  else if (id < root->id)
  {
    root->left = insert(id, root->left);
    if (height(root->left) - height(root->right) == 2)
    {
      if (id < root->left->id)
        root = single_rotate_right(root);
      else
        root = left_right(root);
    }
  }
  else if(id > root->id)
  {
    root->right = insert(id, root->right);
    if (height(root->right) - height(root->left) == 2)
    {
      if (id < root->right->id)
        root = right_left(root);
      else
        root = single_rotate_left(root);
    }
  }

  root->h = max(height(root->left), height(root->right)) + 1;
  return (root);
}

这是一种方法:每个节点包含该节点的高度。这种方法比较简单。

posted @ 2013-09-25 16:47  玩的就是 心跳  阅读(95)  评论(0编辑  收藏  举报