HackerRank "Self Balancing Tree"
2015-11-21 13:42
393 查看
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
View Code
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 = 0; pNew->left = pNew->right = nullptr; return pNew; } int height(node *p) { if(!p) return -1; return p->ht; } int get_height(node *p) { if (!p) return 0; return 1 + 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 0; return height(p->left) - height(p->right); } node *balance(node *p) { int w = balance_factor(p); if (!p || abs(w) < 2) return p; if (w > 0) { if(balance_factor(p->left) < 0) { p->left = left_rotate(p->left); } return right_rotate(p); } else { if(balance_factor(p->right) > 0) { 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); }
View Code
相关文章推荐
- java Java与编码
- C++学习笔记24——泛型算法之find
- :重庆巫山小三峡—小小三峡景区门票价格居然是全国最便宜的!
- The CSS Box Model
- 三大动态网页技术
- 响应式布局 相关
- javascript对闭包的理解
- 代数-方程组
- php 打印功能扩展
- 超像素分割技术发展情况梳理(superpixels segment)
- Codeforces Round #332 (Div. 2)
- MFC基于CSplitterWnd类的多窗口分割
- phonegap-网络访问与调用android手机硬件设备
- 用户注册
- 2015/11/21
- const限定符的用法总结
- R语言安装包地址
- NOIP 2015 简记
- Android学习笔记之浅谈@id与@+id之间的区别
- 《笨办法学python第三版》习题26,原错误代码及正确代码