HackerRank "Self Balancing Tree"
2024-10-21 09:23:33
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);
}
最新文章
- IE7 浏览器下面设置text-indent属性变成margin属性BUG
- Android中Activity的启动模式
- 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
- 【Beta】Daily Scrum 第二天
- .net 服务器端文件下载
- 企业内部从零开始安装docker hadoop 提纲
- HP 电脑装 纯净版的win7
- Eclipse将android项目打包jar文件
- Linux 平台下 YUM 源配置 手册
- SGU481 Hero of Our Time
- React Native专题
- Swift - 列表项尾部附件点击响应(感叹号,箭头等)
- sql关键字之null
- Bootstrap之折叠(Collapse)插件
- Java设计模式之职责链设计模式
- 记忆(缓存)函数返回值:Python 实现
- docker安装,无法正常启动
- os.listdir()、os.walk()和os.mkdir()的用法
- 20165220 Java第六周学习总结
- python处理中文