static AVLNode* rebalanceNode(AVLNode *node){ assert(node != nullptr); // should not be called otherwise if(isBalanced(node)) return node; if(leftHeight(node) < rightHeight(node)) return rightRebalanceNode(node); if(rightHeight(node) < leftHeight(node)) return leftRebalanceNode(node); // should not reach this point assert(false); }
static void updateHeight(AVLNode *node){ assert(node != nullptr); // should not be called otherwise int lh = leftHeight(node); int rh = rightHeight(node); int max = (lh > rh) ? lh : rh; node->setHeight(1 + max); }
static bool isBalanced(const AVLNode *node){ assert(node != nullptr); // should not be called otherwise int lh = leftHeight(node); int rh = rightHeight(node); if (lh > rh + 1) return false; if (rh > lh + 1) return false; return true; }
// checks calculated heights values static bool checkHeightNode(const AVLNode *node){ if (node == nullptr) return true; // no stale height on empty tree if(!checkHeightNode(node->left())) return false; // failure left if(!checkHeightNode(node->right())) return false; // failure right int lh = leftHeight(node); int rh = rightHeight(node); int max = (lh > rh) ? lh : rh; return (node->height() == (1 + max)); }
int Solution::countNodes(TreeNode* root) { int nodesNum; int lHeight = leftHeight(root); int rHeight = rightHeight(root); if(lHeight == rHeight) { nodesNum = (1 << lHeight) - 1; } else { nodesNum = countNodes(root->left) + countNodes(root->right) + 1; } return nodesNum; }
// restores AVL property when node is left-heavy static AVLNode* leftRebalanceNode(AVLNode *node){ assert(node != nullptr); // should not be called otherwise AVLNode *left = node->left(); assert(left != nullptr); // should not be called otherwise if(rightHeight(left) > leftHeight(left)){ // more rebalancing needed AVLNode *temp = leftRotateNode(left); node->setLeft(temp); // new left child for node temp->setParent(node); // corresponding parent link updateHeight(node); // re-calc height after change of child } return rightRotateNode(node); }