经典题集之树四

  1. 将数组转换为二叉搜索树
  2. 平衡树,注意旋转是从失衡的哪个元素开始,不是插入的节点,同时LR,RL旋转是相反的,例如:LR旋转是先R旋转再L旋转。
  3. 向树的左侧子节点的左子树中插入元素,采用LL旋转
  4. 向树的右侧子节点的右子树中插入元素,采用RR旋转
  5. 向x的左侧节点的右子树中插入元素,采用LR旋转
  6. 向x的右侧子节点的左子树中插入元素,采用RL旋转
  7. 判断二叉搜索树是不是AVL
	public Node BuildBinaryTreeFromArray(int [] a,int left,int right) {
		Node temp = new Node();
		int mid;
		if(left > right) return null;
		if(left == right) {
			temp.data = a[left];
			temp.leftchild = temp.rightchild = null;
		}else {
			mid = left+(right-left)/2;
			temp.data = a[mid];
			temp.leftchild = BuildBinaryTreeFromArray(a, left, mid);
			temp.rightchild = BuildBinaryTreeFromArray(a, mid+1, right);
		}
		return temp;
	}
	//2.平衡树,注意旋转是从失衡的哪个元素开始,不是插入的节点,同时LR,RL旋转是相反的,例如:LR旋转是先R旋转再L旋转。
	//向树的左侧子节点的左子树中插入元素,采用LL旋转
	public Node RotateLeft(Node x) {
		Node w = x.leftchild;
		x.leftchild = w.rightchild;
		w.rightchild  = x;
		x.height = Integer.max(Height(x.leftchild), Height(x.rightchild)) + 1;
		w.height = Integer.max(Height(w.leftchild), x.height) + 1;
		return w;
	}
	//向树的右侧子节点的右子树中插入元素,采用RR旋转
	public Node RotateRight(Node x) {
		Node w = x.rightchild;
		x.rightchild = w.leftchild;
		w.leftchild = x;
		w.height = Integer.max(Height(w.rightchild),Height(w.leftchild)) + 1;
		x.height = Integer.max(x.rightchild, w.height) + 1;
		return w;
	}
	//双旋转
	//向x的左侧节点的右子树中插入元素,采用LR旋转
	public Node RotateLeftRight(Node x) {
		x.leftchild = RotateRight(x.leftchild);
		return RotateLeft(x);
	}
	//向x的右侧子节点的左子树中插入元素,采用RL旋转
	public Node RotateRightLeft(Node x) {
		x.rightchild = RotateLeft(x.rightchild);
		return RotateRight(x);
	}
	//3.判断二叉搜索树是不是AVL
	public int IsAVL(Node root) {
		int left,right;
		if(root == null) return 0;
		left = IsAVL(root.leftchild);
		if(left == -1)
			return left;
		right = IsAVL(root.rightchild);
		if(right == -1)
			return right;
		if(Math.abs(left - right) > 1 )
			return -1;
		return Integer.max(left, right) + 1;
	}
	

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值