在HashMap上花了一点时间,1.8之后HashMap使用了红黑树,果然还是要回头看一下各种各样的树结构才行
在数据结构中,数指代一种满足多个特殊条件的无环联通图,满足特定的五个条件的图才能被称为树balabala,有很多种概念相近但是有细微不同的树,比如说有根树有序树啦balabala,不论如何,这里主要是要谈一谈二叉树。
二叉树并不只是有两个节点的有序树,比较典型的区别是缺失左节点或右节点对二叉树有区别,对有序树则无区别。
满二叉树和完全二叉树:
满二叉树:除最后一层无任何子节点外,每一层上的所有结点都有两个子结点。也可以这样理解,除叶子结点外的所有结点均有两个子结点。节点数达到最大值,所有叶子结点必须在同一层上。
满二叉树的性质:
1) 一颗树深度为h,最大层数为k,深度与最大层数相同,k=h;
2) 叶子数为2h;
3) 第k层的结点数是:2k-1;
4) 总结点数是:2k-1,且总节点数一定是奇数。
完全二叉树:若设二叉树的深度为h,除第 h 层外,其它各层 (1~(h-1)层) 的结点数都达到最大个数,第h层所有的结点都连续集中在最左边,这就是完全二叉树。
常用的二叉树:
1.二叉查找树
又称为是二叉排序树(Binary Sort Tree)或二叉搜索树。二叉排序树或者是一棵空树,或者是具有下列性质的二叉树:
1) 若左子树不空,则左子树上所有结点的值均小于它的根结点的值;
2) 若右子树不空,则右子树上所有结点的值均大于或等于它的根结点的值;
3) 左、右子树也分别为二叉排序树;
4) 没有键值相等的节点。
值得注意的是,二叉查找树并没有左右树必须对称的特性,因此,在传入数组较为有序的情况下,该树会退化成链,这个特性会使其查找及添加效率下降,手动实现二叉查找树的代码如下:
public class Tree {
private Node root;
class Node{
int val;
Node leftChild;
Node rightChild;
Node(int val,Node leftChild,Node rightChild){
this.val=val;
this.leftChild=leftChild;
this.rightChild=rightChild;
}
@Override
public String toString() {
return val+"";
}
}
public void init(int[] numbers){
if (numbers==null||numbers.length==0){
return;
}else {
root=new Node(numbers[0],null,null);
}
for (int i=1;i<numbers.length;i++){
add(numbers[i]);
}
}
public void add(int number){
if (root==null){
root=new Node(number,null,null);
return;
}
Node target=root;
while (target!=null){
if (number==target.val){
break;
}
if (number>target.val){
if (target.rightChild==null){
target.rightChild=new Node(number,null,null);
break;
}else {
if (number>target.val){
target=target.rightChild;
}else {
target=target.leftChild;
}
}
}else {
if (target.leftChild==null){
target.leftChild=new Node(number,null,null);
break;
}else {
if (number>target.val){
target=target.rightChild;
}else {
target=target.leftChild;
}
}
}
}
}
/**
* 遍历
*/
public void lterator(){
if (root==null){
System.out.println("empty");
return;
}
lterator(root);
}
private void lterator(Node node){
if (node.leftChild!=null) {
lterator(node.leftChild);
}
System.out.println(node);
if (node.rightChild!=null) {
lterator(node.rightChild);
}
}