сделал дерево AVL, и все работало хорошо, пока я не проверил его с большим количеством вставок. После удаления узла с двумя детьми поле данных в узле, которое «перемещено», получает странное значение. Что я узнал, это неопределенное поведение в C ++. Я понятия не имею, как это сделать. Чего мне не хватает?
сделал дерево AVL, и все работало хорошо, пока я не проверил его с большим количеством вставок. После удаления узла с двумя детьми поле данных в узле, которое «перемещено», получает странное значение. Что я узнал, это неопределенное поведение в C ++. Я понятия не имею, как это сделать. Чего мне не хватает?[code]#include "AVL_Tree.h" #include "stddef.h" #include #include #include
/** *Adds new node to the tree by calling insert() */ void AVL_Tree::add(const int& data) { try { TreeNode* node = new TreeNode(data); this->root = insert(this->root, node); size++; } catch(std::string s) { std::cout leftChild); std::cout data rightChild); } }
/** *Recursively traverse the tree to find the correct place for the new node and then *returns the tree. */ AVL_Tree::TreeNode* AVL_Tree::insert(TreeNode* current, TreeNode* newNode) { if(current == NULL) { return newNode; } if(newNode->data < current->data) { current->leftChild = insert(current->leftChild, newNode); } else if(newNode->data > current->data) { current->rightChild = insert(current->rightChild, newNode); } else { throw std::string("Data already exist in tree"); } //return current; return balance(current); }
/** * Recursively finds the TreeNode that matches 'dataToRemove' and erase it from the tree then returns the new tree */ AVL_Tree::TreeNode* AVL_Tree::remove(TreeNode* current, const int& dataToRemove) { if(current == NULL) { return current; } if(dataToRemove < current->data) { current->leftChild = remove(current->leftChild, dataToRemove); } else if(dataToRemove > current->data) { current->rightChild = remove(current->rightChild, dataToRemove); } else //if(dataToRemove == current->data) { TreeNode* temp = NULL; //No children if(current->leftChild == NULL && current->rightChild == NULL) { delete current; current = NULL; } //One child else if(current->leftChild != NULL && current->rightChild == NULL) { temp = current->leftChild; current->data = temp->data; current->leftChild = remove(current->leftChild, temp->data); } else if(current->leftChild == NULL && current->rightChild != NULL) { temp = current->rightChild; current->data = temp->data; current->rightChild = remove(current->rightChild, temp->data); } //Two children else if(current->leftChild != NULL && current->rightChild != NULL) { temp = findSuccessor(current->rightChild); current->data = temp->data; remove(current->rightChild, temp->data);
} }
return balance(current); }
/** * Returns height of tree */ int AVL_Tree::height(TreeNode* current) { if(current == NULL) { return 0; } return current->height; }
/** * Returns the balance factor for the argument(TreeNode pointer) */ int AVL_Tree::getBalance(TreeNode* current) { if(current == NULL) { return 0; } return height(current->rightChild) - height(current->leftChild); }
/** * Sets the height of the specified TreeNode */ void AVL_Tree::fixHeight(TreeNode* current) { int hl = height(current->leftChild); int hr = height(current->rightChild);
current->height = (hl > hr ? hl : hr) + 1; }
/** * Takes TreeNode pointer as argument and balances the tree if it isn't NULL */ AVL_Tree::TreeNode* AVL_Tree::balance(TreeNode* current) { if (current != NULL) { fixHeight(current); if(getBalance(current) == 2) { if(getBalance(current->rightChild) < 0) { current->rightChild = rotateRight(current->rightChild); } return rotateLeft(current); } if(getBalance(current) == -2) { if(getBalance(current->leftChild) > 0) { current->leftChild = rotateLeft(current->leftChild); } return rotateRight(current); } return current; } else { return NULL; } }
/** * Preforms a left rotation * Returns the rotated subtree */ AVL_Tree::TreeNode* AVL_Tree::rotateLeft(TreeNode* current) { TreeNode* right = current->rightChild; current->rightChild = right->leftChild; right->leftChild = current; fixHeight(current); fixHeight(right); return right; }
/** * Preforms a right rotation */ AVL_Tree::TreeNode* AVL_Tree::rotateRight(TreeNode* current) { TreeNode* left = current->leftChild; current->leftChild = left->rightChild; left->rightChild = current; fixHeight(current); fixHeight(left); return left; }
/** * Takes TreeNode pointer as argument and return the "leftest"(smallest) node in the right subtree. */ AVL_Tree::TreeNode* AVL_Tree::findSuccessor(TreeNode* current) {
В настоящее время я изучаю структуры данных, и у меня возникла проблема с деревом AVL.
Код:
from myqueue import Queue # my custom queue implemented by linked list
Я работаю над реализацией двоичного дерева поиска (BST) в Java, и мне нужно правильно обрабатывать все случаи удаления узлов. Мне нужно обработать следующие случаи:
Узел без дочерних элементов (листовой узел)
Узел с одним дочерним элементом
Узел с...
Я работаю над реализацией двоичного дерева поиска (BST) в Java, и мне нужно правильно обрабатывать все случаи удаления узлов. Мне нужно обработать следующие случаи:
Узел без дочерних элементов (листовой узел)
Узел с одним дочерним элементом
Узел с...
Я пытаюсь решить задачу LeetCode 1448. Подсчитайте хорошие узлы в двоичном дереве:
При наличии корня двоичного дерева узел X в дереве называется good , если на пути от корня до X нет узлов со значением больше > X.
Вернуть количество хороших узлов в...
Я рассматриваю задачу 222 LeetCode. Подсчет полных узлов дерева:
При наличии корня завершенного двоичное дерево, возвращает количество узлов в дереве.
Согласно Википедии, каждый уровень, за исключением, возможно, последнего, полностью заполнен...