AVL Tree永远不会有不平衡的C ++

时间:2014-04-15 20:59:57

标签: c++ avl-tree

所以我正在制作一个自平衡的AVL树,我正在实现它就像我已经看到许多其他AVL树实现的那样,但当我去平衡树时,我的函数返回树是平衡的当它显然不是。

这是我的AVLTree课程:

#include "AVLTree.h"
#include "Node.h"
#include <iostream>

using namespace std;

AVLTree::AVLTree(void)
{
  root = nullptr;
}

Node* AVLTree::GetRoot()
{
  return root;
}

Node* AVLTree::RotateLeft(Node *root)
{
  Node *temp = root;
  root = temp->GetRight();
  temp->SetRight(root->GetLeft());
  root->SetLeft(temp);
  return root;
}

Node* AVLTree::RotateRight(Node *root)
{
  Node *temp = root;
  root = temp->GetLeft();
  temp->SetLeft(root->GetRight());
  root->SetLeft(temp);
  return root;
}

Node* AVLTree::DoubleRight(Node *root)
{
  RotateLeft(root->GetLeft());
  RotateRight(root);
  return root;
}

Node* AVLTree::DoubleLeft(Node *root)
{
  RotateRight(root->GetRight());
  RotateLeft(root);
  return root;
}

void AVLTree::Add(int value, Node *r)
{
  Node *node;
  if (r == nullptr)
    node = root;
  if (root == nullptr)
  {
    root = new Node(value);
    return;
  }

  if (value < node->GetValue())
  {
    if (node->GetLeft() == nullptr)
    {
      node->SetLeft(new Node(value));
      node = MakeBalance(node);
    }
    else
    {
      Add(value, node->GetLeft());
      node = MakeBalance(node);
    }
  }

  else if (node->GetRight() == nullptr)
  {
    node->SetRight(new Node(value));
    node = MakeBalance(node);
  }

  else
  {
    Add(value, node->GetRight());
    node = MakeBalance(node);
  }
}

void AVLTree::Traverse(Node *node)
{
  cout << node->GetValue() << ", ";
  if (node->GetLeft() != nullptr)
    Traverse(node->GetLeft());
  if (node->GetRight() != nullptr)
    Traverse(node->GetRight());
}

int AVLTree::CheckHeight(Node *node)
{
  int height = 0;
  if (node != nullptr)
  {
    int left = CheckHeight(node->GetLeft());
    int right = CheckHeight(node->GetRight());
    height = max(left, right) + 1;
  }
  return height;
}

int AVLTree::GetDifference(Node *node)
{
  int left = CheckHeight(node);
  int right = CheckHeight(node);
  int balance = left - right;
  return balance;
}

Node* AVLTree::MakeBalance(Node *node)
{
  int balance = GetDifference(node);
  if (balance > 1)
  {
    if (GetDifference(node->GetLeft()) > 0)
      node = RotateLeft(node);
    else
      node = DoubleLeft(node);
  }
  else if (balance < -1)
  {
    if (GetDifference(node->GetRight()) > 0)
      node = DoubleRight(node);
    else
      node = RotateRight(node);
  }
  return node;
}

我已经介绍了几次,并且它继续返回左边的余额为2,并且在我添加3,5,然后10之后,正确的平衡是2,使得树的正确平衡为2。

1 个答案:

答案 0 :(得分:2)

这部分跳出来对我说:

int AVLTree::GetDifference(Node *node)
{
    int left = CheckHeight(node);
    int right = CheckHeight(node);
    int balance = left - right;
    return balance;
}

这将始终导致left == right,因此left - right == 0

你忘了传给孩子们:

// You might want this too: if (!node) return 0;
int left = CheckHeight(node->GetLeft());
int right = CheckHeight(node->GetRight());
int balance = left - right;
return balance;