Something to learn: Rotation ops in AVL tree does not require recursion
https://github.com/andreimaximov/hacker-rank/blob/master/data-structures/tree/self-balancing-tree/main.cpp

node *create_node(int val)
{
node *pNew = new node;
pNew->val = val;
pNew->ht = ;
pNew->left = pNew->right = nullptr; return pNew;
} int height(node *p)
{
if(!p) return -;
return p->ht;
} int get_height(node *p)
{
if (!p) return ;
return + max(height(p->left), height(p->right));
} node *right_rotate(node *p)
{
node *pOrigRoot = p;
node *root = p->left;
pOrigRoot->left = root->right;
root->right = pOrigRoot; pOrigRoot->ht = get_height(pOrigRoot);
root->ht = get_height(root); return root;
} node *left_rotate(node *p)
{
node *pOrigRoot = p;
node *root = p->right;
pOrigRoot->right = root->left;
root->left = pOrigRoot; pOrigRoot->ht = get_height(pOrigRoot);
root->ht = get_height(root); return root;
} int balance_factor(node *p)
{
if (!p) return ;
return height(p->left) - height(p->right);
} node *balance(node *p)
{
int w = balance_factor(p); if (!p || abs(w) < )
return p; if (w > )
{
if(balance_factor(p->left) < )
{
p->left = left_rotate(p->left);
}
return right_rotate(p);
}
else
{
if(balance_factor(p->right) > )
{
p->right = right_rotate(p->right);
}
return left_rotate(p);
} return p;
} node * insert(node * root,int val)
{
if (val < root->val)
{
if(!root->left)
{
root->left = create_node(val);
}
else
{
root->left = insert(root->left, val);
}
}
else
{
if(!root->right)
{
root->right = create_node(val);
}
else
{
root->right = insert(root->right, val);
}
}
root->ht = get_height(root); return balance(root);
}

最新文章

  1. IE7 浏览器下面设置text-indent属性变成margin属性BUG
  2. Android中Activity的启动模式
  3. java.lang.UnsatisfiedLinkError: C:\apache-tomcat-8.0.21\bin\tcnative-1.dll: Can&#39;t load IA 32-bit .dll on a AMD 64-bit platform
  4. 【Beta】Daily Scrum 第二天
  5. .net 服务器端文件下载
  6. 企业内部从零开始安装docker hadoop 提纲
  7. HP 电脑装 纯净版的win7
  8. Eclipse将android项目打包jar文件
  9. Linux 平台下 YUM 源配置 手册
  10. SGU481 Hero of Our Time
  11. React Native专题
  12. Swift - 列表项尾部附件点击响应(感叹号,箭头等)
  13. sql关键字之null
  14. Bootstrap之折叠(Collapse)插件
  15. Java设计模式之职责链设计模式
  16. 记忆(缓存)函数返回值:Python 实现
  17. docker安装,无法正常启动
  18. os.listdir()、os.walk()和os.mkdir()的用法
  19. 20165220 Java第六周学习总结
  20. python处理中文

热门文章

  1. editplus 常用快捷键汇总 大小写代码折叠
  2. Bash Shell字符串操作小结
  3. UI学习笔记---第八天
  4. 2016 ACM/ICPC Asia Regional Dalian Online 1002/HDU 5869
  5. tyvj1014 - 乘法游戏 ——记忆化搜索DP
  6. PHP 的 HMAC_SHA1算法 实现
  7. Text 绑定
  8. 【BZOJ2013】【JSOI2008】球形空间产生器
  9. &lt;C Traps and Pitfalls&gt;笔记
  10. netsh winsock reset