二叉树的遍历
广度优先遍历
层次遍历,每一层从左到右依次遍历
public static void ceng(Node tree){
Queue<Node> queue = new LinkedList<>();
Node node;
if(tree == null) {
return;
}
queue.add(tree);
while (!queue.isEmpty()){
node = queue.peek();
queue.poll();
if(node.left != null){
queue.add(node.left);
}
if(node.right != null){
queue.add(node.right);
}
System.out.print(node.value + " ");
}
}
深度优先遍历
先序遍历:根左右
public static void xian(Node tree){
if(tree == null){
return;
}
System.out.print(tree.value + " ");
xian(tree.left);
xian(tree.right);
}
中序遍历:左根右
public static void zhong(Node tree){
if(tree == null){
return;
}
zhong(tree.left);
System.out.print(tree.value + " ");
zhong(tree.right);
}
后序遍历:左右根
public static void hou(Node tree){
if(tree == null){
return;
}
xian(tree.left);
xian(tree.right);
System.out.print(tree.value + " ");
}
二叉搜索树
特点(二叉树本身是没有顺序的)
①要有根节点
②和父节点相比,比父节点小的放在当前节点的左孩子
③和父节点相比,比父节点大的放在当前节点的右孩子
时间复杂度
查询(O(logn))
二分法查询,时间复杂度为O(logn)。
若只有左子树或者右子树,则时间复杂度为O(n),由此引出平衡二叉树,解决时间复杂度高的问题。
①和根结点比较。
②如果相等,就找到了。
③如果小(大),和左(右)子树比较,直到找到相等的,如果没找到,也没有东西可以比,就没有找到。
public static void find(Node tree,int x){
if(x < tree.value){
if(tree.left == null){
System.out.println("没有找到" + x);
}else{
find(tree.left,x);
}
}else if(x > tree.value){
if(tree.right == null){
System.out.println("没有找到" + x);
}else{
find(tree.right,x);
}
}else {
System.out.println("找到了" + x);
}
}
增加(O(logn))
①先创建一个结点。
②判断应放在左边还是右边。
③判断如果左(右)孩子为空,就直接放,如果不为空递归add方法,和左(右)孩子比较,一直递归下去,直到找到可以放的位置。
public static void add(Node tree,int x) {
Node node = new Node(x);
if(x <= tree.value){
if(tree.left == null){
tree.left = node;
}else{
add(tree.left,x);
}
}else{
if(tree.right == null){
tree.right = node;
}else{
add(tree.right,x);
}
}
}
删除(O(logn))
平衡二叉树
平衡因子=|根节点的左树高度-右树高度| < 2
二叉树转化为平衡二叉树
LL型调整策略:
①找到离造成不平衡的结点最近的不平衡结点(不平衡指|平衡因子| >= 2)
②将其左孩子提升为新的根节点
③将原来的根节点降为新的根节点的右孩子
④各子树按大小关系连接
RR型调整策略:
①找到离造成不平衡的结点最近的不平衡结点(不平衡指|平衡因子| >= 2)
②将其右孩子提升为新的根节点
③将原来的根节点降为新的根节点的左孩子
④各子树按大小关系连接
LR型调整策略:
①找到离造成不平衡的结点最近的不平衡结点(不平衡指|平衡因子| >= 2)
②将此结点的左子树的右子树变为不平衡节点左子树的父结点
③旋转的结果是LL型
④按照LL型进行调整
RL型调整策略:
①找到离造成不平衡的结点最近的不平衡结点(不平衡指|平衡因子| >= 2)
②将此结点的右子树的左子树变为不平衡节点右子树的父结点
③旋转的结果是RR型
④按照RR型进行调整
红黑树(自平衡二叉树)
由来
当插入越来越多得数据时,需要查找和移动大量的数据来使该二叉树达到平衡,为了解决这一问题,引入红黑树,通过变色,左旋,右旋达到平衡。