使用Java实现平衡二叉树

使用Java实现平衡二叉树

二叉树是一种较为复杂的数据结构,二叉树算法在数据查询时的时间复杂度为
O(log n)(n为保存元素个数).
但是普通的二叉树在数据添加和删除时很容易出现树结构不平衡问题
,而使用平衡二叉树则不会出现这样的问题.

如何实现?

我们通过旋转完成
如:左旋转
怎么处理-进行左旋转

1.创建一个新的节点newnode(以4这个值创建),创建一个新的节点,值等于当前根节点的值

//把新节点的左子树设置了当前节点的左子树

2.newnode.left=left

//把新节点的右子树设置为当前节点的右子树的左子树

3.newnode.right=right.left

把当前节点的值换为右子节点的值

4.value=right.value

//把当前节点的右子树设置为右子树的右子树

5.right=right.right

把当前节点的左子树设置为新节点

6.left=newnode

平衡二叉树

具体代码:

public class BalancedBinaryTree<T> {
    private int size;
    private Node root;
    @SuppressWarnings("rawtypes")
	private Comparator comparator;

    public BalancedBinaryTree() {

    }

    @SuppressWarnings("rawtypes")
	public BalancedBinaryTree(Comparator comparator) {
        this.comparator = comparator;
    }
    
    public void add(T data) {
        Node node = new Node(data);
        Node p = findNode(node);
        if (p == null) {
            this.root = node;
        } else if (p.compare(node) > 0) {
            p.left = node;
            node.parent = p;
        } else if (p.compare(node) < 0) {
            p.right = node;
            node.parent = p;
        } else {
            p.data = data;
            return;
        }
        size++;
        handleImBalance4Add(node);
    }

    public boolean remove(T data) {
        if (root == null) {
            return false;
        }
        Node node = new Node(data);
        Node res = findNode(node);
        if (node.compare(res) != 0) {
            throw new NoSuchElementException();
        }
        Node checkPoint;
        if (res.left == null && res.right == null) {
            checkPoint = removeLeafNode(res);
        } else if (res.left == null || res.right == null) {
            checkPoint = removeNodeWithOneChild(res);
        } else {
            checkPoint = removeNodeWithTwoChild(res);
        }
        if (checkPoint != null) {
            handleImbalance4Remove(checkPoint);
        }
        size--;
        return true;
    }

    public int size() {
        return size;
    }

    private void handleImbalance4Remove(Node checkPoint) {
        Node tmp = checkPoint;
        boolean leftRemoved = false;
        if (tmp.left == null && tmp.right == null) {
            tmp.factor = 0;
            if (tmp.parent != null) {
                leftRemoved = tmp.parent.left == tmp;
            }
            tmp = tmp.parent;
        } else if (tmp.factor == 0) {
            tmp.factor = tmp.left == null ? 1 : -1;
            return;
        } else {
            leftRemoved = tmp.left == null;
        }
        int f;
        while (tmp != null) {
            f = tmp.factor;

            if (leftRemoved) {
                f = f + 1;
            } else {
                f = f - 1;
            }
            tmp.factor = f;
            if (f == -2 || f == 2) {
                tmp = handleImbalance(tmp);
            } else if (f == 1 || f == -1) {
                break;
            }
            leftRemoved = tmp.parent != null && tmp.parent.left == tmp;
            tmp = tmp.parent;
        }
    }

    private Node removeNodeWithTwoChild(Node node) {
        if (node.left == null || node.right == null) {
            throw new IllegalStateException("only use of two child node removing");
        }
        Node target = findDeepestAndClosestNodeOfCurrentNode(node);
        node.data = target.data;
        Node p = null;
        if (target.left == null && target.right == null) {
            p = removeLeafNode(target);
        } else if (target.left == null || target.right == null) {
            p = removeNodeWithOneChild(target);
        } else {
            //impossible
            throw new IllegalStateException("method of findDeepestAndClosestNodeOfCurrentNode work not right!");
        }
        return p;
    }

    private Node removeNodeWithOneChild(Node node) {
        Node parent = node.parent;
        Node child;
        if (node.left == null && node.right != null) {
            child = node.right;
        } else if (node.right == null && node.left != null) {
            child = node.left;
        } else {
            throw new IllegalStateException("only use of one child node removing");
        }
        child.parent = parent;
        if (parent == null) {
            root = child;
        } else if (parent.left == node) {
            parent.left = child;
        } else {
            parent.right = child;
        }
        return child;
    }

    private Node removeLeafNode(Node node) {
        if (node.left != null || node.right != null) {
            throw new IllegalStateException("only use of leaf child node removing");
        }
        Node parent = node.parent;
        if (parent != null) {
            if (parent.left == node) {
                parent.left = null;
            } else {
                parent.right = null;
            }
        } else {
            root = null;
        }
        return parent;
    }

    private Node findDeepestAndClosestNodeOfCurrentNode(Node node) {
        Node left = node.left;
        Node right = node.right;
        int i = 0, j = 0;
        Node targetLeft = left, targetRight = right;
        boolean bottom = false;
        for (; ; i++) {
            if (left.right != null) {
                left = left.right;
            } else {
                if (!bottom) {
                    targetLeft = left;
                    bottom = true;
                }
                if (left.left != null) {
                    left = left.left;
                } else {
                    break;
                }
            }
        }
        bottom = false;
        for (; ; j++) {
            if (right.left != null) {
                right = right.left;
            } else {
                if (!bottom) {
                    targetRight = right;
                    bottom = true;
                }
                if (right.right != null) {
                    right = right.right;
                } else {
                    break;
                }
            }
        }
        if (i >= j) {
            return targetLeft;
        } else {
            return targetRight;
        }
    }

    private void handleImBalance4Add(Node checkPoint) {
        Node tmp = checkPoint;
        Node p = tmp.parent;
        boolean tmpLeftFlag;
        int k;
        while (p != null) {
            tmpLeftFlag = p.left == tmp;
            if (tmpLeftFlag) {
                k = p.factor - 1;
            } else {
                k = p.factor + 1;
            }
            p.factor = k;
            if (k == 2 || k == -2) {
                handleImbalance(p);
                break;
            } else if (k == 0) {
                break;
            }
            tmp = p;
            p = p.parent;
        }
    }

    private Node handleImbalance(Node node) {
        Node res;
        int rotateType;
        int k = 0;
        if (node.factor == -2 && node.left.factor == -1) {
            res = RRR(node);
            rotateType = 1;
        } else if (node.factor == 2 && node.right.factor == 1) {
            res = LLR(node);
            rotateType = 2;
        } else if (node.factor == -2 && node.left.factor == 1) {
            k = node.left.right.factor;
            res = LRR(node);
            rotateType = 3;
        } else if (node.factor == 2 && node.right.factor == -1) {
            k = node.right.left.factor;
            res = RLR(node);
            rotateType = 4;
        } else {
            throw new RuntimeException("平衡因子计算错误");
        }
        handleFactorAfterReBalance(res, rotateType, k);
        return res;
    }

    private void handleFactorAfterReBalance(Node node, int rotateType, int originFactor) {
        node.factor = 0;
        if (rotateType == 1) {
            node.right.factor = 0;
        } else if (rotateType == 2) {
            node.left.factor = 0;
        } else if (rotateType == 3 || rotateType == 4) {
            if (originFactor == 1) {
                node.left.factor = -1;
                node.right.factor = 0;
            } else if (originFactor == -1) {
                node.left.factor = 0;
                node.right.factor = 1;
            } else {
                node.left.factor = 0;
                node.right.factor = 0;
            }
        }
    }

    private Node RRR(Node node) {
        Node parent = node.parent;
        Node child = node.left;
        child.parent = parent;
        node.parent = child;
        node.left = child.right;
        if (node.left != null) {
            node.left.parent = node;
        }
        child.right = node;
        if (parent == null) {
            root = child;
        } else if (parent.right == node) {
            parent.right = child;
        } else {
            parent.left = child;
        }
        return child;
    }

    private Node LLR(Node node) {
        Node parent = node.parent;
        Node child = node.right;
        child.parent = parent;
        node.parent = child;
        node.right = child.left;
        if (node.right != null) {
            node.right.parent = node;
        }
        child.left = node;
        if (parent == null) {
            root = child;
        } else if (parent.left == node) {
            parent.left = child;
        } else {
            parent.right = child;
        }
        return child;
    }

    private Node LRR(Node node) {
        LLR(node.left);
        return RRR(node);
    }

    private Node RLR(Node node) {
        RRR(node.right);
        return LLR(node);
    }

    private Node findNode(Node node) {
        Node p = null;
        Node tmp = root;
        while (tmp != null) {
            p = tmp;
            if (tmp.compare(node) > 0) {
                tmp = tmp.left;
            } else if (tmp.compare(node) < 0) {
                tmp = tmp.right;
            } else {
                break;
            }
        }
        return p;
    }

    private void traverse(Node node, Consumer<Node> consumer) {
        if (node == null) {
            return;
        }
        Deque<Node> nodeDeque = new ArrayDeque<>();
        node.height = 1;
        nodeDeque.add(node);
        while (nodeDeque.size() > 0) {
            Node first = nodeDeque.pollFirst();
            consumer.accept(first);
            Node right = first.right;
            if (right != null) {
                right.height = first.height + 1;
                nodeDeque.addFirst(right);
            }
            Node left = first.left;
            if (left != null) {
                left.height = first.height + 1;
                nodeDeque.addFirst(left);
            }
        }
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        traverse(root, n -> {
            for (int i = 0; i < n.height; i++) {
                res.append("----------");
            }
            res.append(':');
            res.append(n.data);
            res.append('(');
            res.append(n.factor);
            res.append(')');
            res.append('\n');
        });
        return res.toString();
    }

    private int getMaxHeight(Node node){
        int[] height = new int[1];
        traverse(node,n->{
            if(n.left == null && n.right == null && n.height > height[0]){
                height[0] = n.height;
            }
        });
        return height[0];
    }
    
    //查询
	public boolean contains(Comparable<T> data) {
		if (this.size == 0) {									// 没有数据
			return false ;										// 结束查询
		}
		return this.root.containsNode(data) ; 					// Node类查询
	}

    class Node {
        private Node parent;
        private Node left;
        private Node right;
        private int factor;
        private int height;
        private T data;

        public Node(T data) {
            Objects.requireNonNull(data);
            this.data = data;
        }

        public int compare(Node target) {
            if (comparator != null) {
                return comparator.compare(this.data, target.data);
            } else {
                return ((Comparable) this.data).compareTo(target.data);
            }
        }

        @Override
        public String toString() {
            return data.toString();
        }
        public boolean containsNode(Comparable<T> data) {
			if (data.compareTo((T) this.data) == 0) {			// 数据匹配
				return true; 									// 查找到了
			} else if (data.compareTo((T) this.data) < 0) { 	// 左子节点查询
				if (this.left != null) {						// 左子节点存在
					return this.left.containsNode(data);		// 递归调用
				} else {										// 没有左子节点
					return false;								// 无法找到
				}
			} else { 											// 右子节点查询
				if (this.right != null) {						// 右子节点存在
					return this.right.containsNode(data);		// 递归调用
				} else {										// 没有右子节点
					return false;								// 无法找到
				}
			}
		}
    }

    static BalancedBinaryTree<Integer> buildTestTree() {
        BalancedBinaryTree<Integer> binaryTree = new BalancedBinaryTree();
        binaryTree.add(8);
        binaryTree.add(3);
        binaryTree.add(13);
        binaryTree.add(1);
        binaryTree.add(5);
        binaryTree.add(10);
        binaryTree.add(16);
        binaryTree.add(2);
        binaryTree.add(4);
        binaryTree.add(7);
        binaryTree.add(9);
        binaryTree.add(12);
        binaryTree.add(15);
        binaryTree.add(18);
        binaryTree.add(6);
        binaryTree.add(11);
        binaryTree.add(14);
        binaryTree.add(17);
        binaryTree.add(19);
        binaryTree.add(20);
        return binaryTree;
    }

实例:

public class Binary {
	public static void main(String args[]) {
		 BalancedBinaryTree<Integer> bbt = new BalancedBinaryTree<>();
	     bbt.add(100);
	     bbt.add(10);
	     bbt.add(40);
	     bbt.add(34);
	     bbt.add(210);
	     System.out.println(bbt);
	}
}

使用自定义数据结构

那我们实现自己类信息的排列呢?
很简单,只需将类加入Comparable接口就可以了

public class Emp implements Comparable<Emp>{
	private String ename ;
	private String job ;
	private Double salary ;
	private Integer age ;
	private Date hiredate ; 
	private String dept ;
	public String getEname() {
		return ename;
	}
	public void setEname(String ename) {
		this.ename = ename;
	}
	public String getJob() {
		return job;
	}
	public void setJob(String job) {
		this.job = job;
	}
	public Double getSalary() {
		return salary;
	}
	public void setSalary(Double salary) {
		this.salary = salary;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public Date getHiredate() {
		return hiredate;
	}
	public void setHiredate(Date hiredate) {
		this.hiredate = hiredate;
	}
	public String getDept() {
		return dept;
	}
	public void setDept(String dept) {
		this.dept = dept;
	}
	@Override
	public int compareTo(Emp emp) {
		return this.age - emp.age;
	}
@Override
	public String toString() {
		return "Emp [ename=" + ename + ", job=" + job + ", salary=" + salary + ", age=" + age + ", hiredate=" + hiredate
				+ ", dept=" + dept + "]";
	}
}

主类(我这里使用了自己做的一个属性自动配置工具):

public class Binary {
	public static void main(String args[]) {
	     System.out.println("使用自定义数据");
	     BalancedBinaryTree<Emp> b = new BalancedBinaryTree<>();
	     String value = "ename:Smith|job:Clerk|salary:8960.00|age:30|hiredate:2003-10-15|"
					+ "dept.dname:财务部|dept.loc:MLDN|dept.company.name:SMD" ;
	     String value2 = "ename:231213|job:Clerk|salary:8960.00|age:24|hiredate:2003-10-15|"
					+ "dept.dname:财务部|dept.loc:MLDN|dept.company.name:SMD" ;
		Emp emp = ClassInstanceFactory.create(Emp.class, value) ;	// 工具类自动设置
		Emp emp2 = ClassInstanceFactory.create(Emp.class, value2) ;	// 工具类自动设置
		String value3 = "ename:23|job:Clerk|salary:8960.00|age:43|hiredate:2003-10-15|"
						+ "dept.dname:财务部|dept.loc:MLDN|dept.company.name:Alibaba" ;
		Emp emp3 = ClassInstanceFactory.create(Emp.class, value3) ;	// 工具类自动设置
		String value4 = "ename:23|job:Clerk|salary:8960.00|age:43|hiredate:2003-10-15|"
				+ "dept.dname:财务部|dept.loc:MLDN|dept.company.name:Alibaba" ;
		Emp emp4 = ClassInstanceFactory.create(Emp.class, value4) ;	// 工具类自动设置
		b.add(emp);
		b.add(emp2);
		b.add(emp3);
	    System.out.println(b);
	    System.out.println(b.contains(emp4));//寻找存不存在和emp4一个属性的对象
	}
}

如果感觉有用就请给我点个免费的赞吧❥(^_-)

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
平衡二叉树(AVL树)是一种自平衡的二叉搜索树,它的左子树和右子树的高度差不超过1。在Java中,可以通过以下步骤实现平衡二叉树: 1. 定义节点类:首先定义一个节点类,包含节点值、左子节点和右子节点等属性。 ```java class Node { int value; Node left; Node right; public Node(int value) { this.value = value; this.left = null; this.right = null; } } ``` 2. 实现平衡二叉树类:创建一个平衡二叉树类,包含插入节点、删除节点、旋转操作等方法。 ```java class AVLTree { private Node root; // 插入节点 public void insert(int value) { root = insertNode(root, value); } private Node insertNode(Node root, int value) { if (root == null) { return new Node(value); } if (value < root.value) { root.left = insertNode(root.left, value); } else if (value > root.value) { root.right = insertNode(root.right, value); } else { // 如果存在相同值的节点,可以根据需求进行处理 return root; } // 更新节点的高度 root.height = 1 + Math.max(getHeight(root.left), getHeight(root.right)); // 平衡操作 int balance = getBalance(root); // 左左情况,进行右旋操作 if (balance > 1 && value < root.left.value) { return rightRotate(root); } // 右右情况,进行左旋操作 if (balance < -1 && value > root.right.value) { return leftRotate(root); } // 左右情况,先左旋再右旋 if (balance > 1 && value > root.left.value) { root.left = leftRotate(root.left); return rightRotate(root); } // 右左情况,先右旋再左旋 if (balance < -1 && value < root.right.value) { root.right = rightRotate(root.right); return leftRotate(root); } return root; } // 删除节点 public void delete(int value) { root = deleteNode(root, value); } private Node deleteNode(Node root, int value) { // 空树或未找到节点 if (root == null) { return root; } if (value < root.value) { root.left = deleteNode(root.left, value); } else if (value > root.value) { root.right = deleteNode(root.right, value); } else { // 找到要删除的节点 // 节点只有一个子节点或无子节点 if (root.left == null || root.right == null) { Node temp = null; if (temp == root.left) { temp = root.right; } else { temp = root.left; } // 无子节点的情况 if (temp == null) { temp = root; root = null; } else { // 一个子节点的情况 root = temp; } } else { // 节点有两个子节点,找到右子树中最小的节点 Node temp = minValueNode(root.right); // 将右子树中最小节点的值赋给要删除的节点 root.value = temp.value; // 删除右子树中最小的节点 root.right = deleteNode(root.right, temp.value); } } // 更新节点的高度 root.height = 1 + Math.max(getHeight(root.left), getHeight(root.right)); // 平衡操作 int balance = getBalance(root); // 左左情况,进行右旋操作 if (balance > 1 && getBalance(root.left) >= 0) { return rightRotate(root); } // 左右情况,先左旋再右旋 if (balance > 1 && getBalance(root.left) < 0) { root.left = leftRotate(root.left); return rightRotate(root); } // 右右情况,进行左旋操作 if (balance < -1 && getBalance(root.right) <= 0) { return leftRotate(root); } // 右左情况,先右旋再左旋 if (balance < -1 && getBalance(root.right) > 0) { root.right = rightRotate(root.right); return leftRotate(root); } return root; } // 获取节点的高度 private int getHeight(Node node) { if (node == null) { return 0; } return node.height; } // 获取节点的平衡因子 private int getBalance(Node node) { if (node == null) { return 0; } return getHeight(node.left) - getHeight(node.right); } // 右旋操作 private Node rightRotate(Node y) { Node x = y.left; Node T2 = x.right; x.right = y; y.left = T2; y.height = Math.max(getHeight(y.left), getHeight(y.right)) + 1; x.height = Math.max(getHeight(x.left), getHeight(x.right)) + 1; return x; } // 左旋操作 private Node leftRotate(Node x) { Node y = x.right; Node T2 = y.left; y.left = x; x.right = T2; x.height = Math.max(getHeight(x.left), getHeight(x.right)) + 1; y.height = Math.max(getHeight(y.left), getHeight(y.right)) + 1; return y; } // 获取最小值节点 private Node minValueNode(Node node) { Node current = node; while (current.left != null) { current = current.left; } return current; } } ``` 以上是一个简单的平衡二叉树Java实现,包括插入节点、删除节点、旋转操作等方法。你可以根据需要进行调整和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Spasol

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值