标签:node 左子 专题 right 二叉树 include root left
Complete Binary Search Tree (30)
Link
这道题相当于是已知完全二叉排序树的中序遍历,要输出其层序遍历。做法很巧妙,根本不用建树。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
#include <cmath>
#include <unordered_set>
using namespace std;
int n,cur;
int a[1010],b[1010];
void levelTraverse(int r){
if(r<=n){
levelTraverse(r<<1);
b[r]=a[++cur];
levelTraverse((r<<1)+1);
}
}
int main() {
scanf("%d",&n);
for(int i=1;i<=n;++i)
scanf("%d",&a[i]);
sort(a+1,a+1+n);
levelTraverse(1);
for(int i=1;i<n;++i)
printf("%d ",b[i]);
printf("%d\n",b[n]);
return 0;
}
Root of AVL Tree (25)
Link
AVL模板题
借用网上的图在此解释一下4种旋转的情形:(左右图都是不平衡的AVL)
先左旋后右旋指的是先左旋左子树,后右旋根节点。实际上左子树是平衡的,但是左孩子(左子树的根节点)满足两边高度之差等于1,这就导致了根节点不平衡。如果左孩子的右子树高度比左子树高度大1,那么就要先左旋以左孩子为根节点的左子树(这就会让新的左孩子的左子树高度比右子树高度大1);如果左孩子的左子树高度比右子树高度大1,那么就不必进行任何操作。也就是说,这种情况下首先要让长度的不平衡集中到左孩子的左边,最后将根节点右旋即可。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
#include <cmath>
using namespace std;
struct node{
int val;
struct node *left,*right;
};
//return root
//左旋的情况:根节点所在的树不平衡
node *rotateLeft(node *root){
node *t=root->right;
root->right=t->left;
t->left=root;
return t;
}
node *rotateRight(node *root){
node *t=root->left;
root->left=t->right;
t->right=root;
return t;
}
//先左旋后右旋的情况:先左旋左子树,后右旋根节点
//左子树平衡,但左子树的两边高度差是1,导致了根节点不平衡
node *rotateLeftRight(node *root){
//先在左子树上完成左旋
root->left=rotateLeft(root->left);
//后右旋根节点
return rotateRight(root);
}
node *rotateRightLeft(node *root){
root->right=rotateRight(root->right);
return rotateLeft(root);
}
int getHeight(node *root){
if(root==NULL) return 0;
return max(getHeight(root->left),getHeight(root->right))+1;
}
node *insert(node *root,int val){
if(root==NULL){
root=new node();
root->val=val;
root->left=root->right=NULL;
}else if(val<root->val){
root->left=insert(root->left,val);
if(getHeight(root->left)-getHeight(root->right)==2)
root=val<root->left->val?rotateRight(root):rotateLeftRight(root);
}else{
root->right=insert(root->right,val);
if(getHeight(root->right)-getHeight(root->left)==2)
root=val<root->right->val?rotateRightLeft(root):rotateLeft(root);
}
return root;
}
int main() {
int n,val;
scanf("%d",&n);
node *root=NULL;
for(int i=1;i<=n;++i){
scanf("%d",&val);
root=insert(root,val);
}
printf("%d\n",root->val);
return 0;
}
标签:node,左子,专题,right,二叉树,include,root,left 来源: https://www.cnblogs.com/preccrep/p/16398174.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。