Binary base + (Comparable, Compartor (increase))

table of Contents

Binary Tree

definition:

1. Full Binary: depth is k, the binary tree and has 2 ^ k-1 nodes, the characteristics of this tree is the number of nodes on the maximum number of nodes in each layer.

Here Insert Picture Description

Complete binary tree 2.: In a binary tree, except for the last layer, if the remaining layers are full, and is full or the last layer, or the lack of a number of consecutive nodes on the right, with n nodes complete binary tree of depth for the floor (log2n) +1. K is a complete binary tree of depth, at least 2k-1 th leaf node, at most 2k-1 nodes.
Here Insert Picture Description

3. The root node (no parent): A is the root node in FIG, B, C is a child node of A.
    Leaf node (no children): FIG H, I, J, F, G is a leaf node.
    B is a child node of A, is the parent node D

Example:

TwoImpl:

interface Two<T> {
    public void add(T data);

    public int size();

    public Object[] toArray();
}

class TwoImpl<T> implements Two<T> {
    private Node root;  //根节点
    private int size;
    private int footer;
    private Object[] resultData;
    @Override
    public void add(T data) {
        if (data == null) {
            return;
        }
        Node node = new Node((Comparable) data);
        if (this.root == null) {    //根节点
            this.root = node;
        } else {
            this.root.addNode(this.root, node);
        }
        ++this.size;
    }

    @Override
    public int size() {
        return this.size;
    }

    @Override
    public Object[] toArray() {
        if(this.size() == 0){
            return null;
        }
        this.footer = 0;
        this.resultData = new Object[this.size];
        this.root.toArrayNode();
        return this.resultData;
    }

    private class Node {
        private Comparable<T> data; //数据
        private Node left;      //左节点
        private Node right;     //右节点
        private Node parent;    //父节点

        public Node(Comparable<T> data) {
            this.data = data;
        }

        /**
         * this.data
         * @param parentNode  父节点
         * @param node  内部类实例(用于传递data数据)
         */
        public void addNode(Node parentNode, Node node) {
            if (this.data.compareTo((T) node.data) <= 0) {  //当前节点this.root小于传入节点
                if (this.right == null) {
                    this.right = node;
                    this.parent = parentNode;
                } else {
                    this.right.addNode(this, node);
                }
            } else {
                if (this.left == null) {
                    this.left = node;
                    this.parent = parentNode;
                } else {
                    this.left.addNode(this, node);
                }
            }
        }

        public void toArrayNode() { //中序解析
            if(this.left != null){  //把左边的数据全部取出再去右边的
                this.left.toArrayNode();
            }
        TwoImpl.this.resultData[TwoImpl.this.footer++] = this.data;
            if(this.right!=null){   //左边的数据取完后才会进入右边
                this.right.toArrayNode();
            }
        }
    }
}

public class Demo01 {
    public static void main(String[] args) {
        Two<Member> two = new TwoImpl<>();
        two.add(new Member("孙七", 27));
        two.add(new Member("赵六", 26));
        two.add(new Member("王五", 25));
        two.add(new Member("张三", 23));
        two.add(new Member("李四1", 24));
        two.add(new Member("李四2", 55));
        two.add(new Member("李四3", 40));
        two.add(new Member("李四4", 38));
        two.add(new Member("李四5", 29));
        two.add(new Member("李四6", 21));
        two.add(new Member("李四7", 19));
        two.add(new Member("李四11", 62));
        two.add(new Member("李四8", 51));
        two.add(new Member("李四9", 34));
        two.add(new Member("李四10", 56));
        two.add(new Member("李四12", 72));
        two.add(new Member("李四13", 45));
        two.add(new Member("李四14", 33));
        two.add(new Member("李四15", 31));
        System.out.println(Arrays.toString(two.toArray()));
    }
}

Member:

public class Member implements Comparable<Member> {
    private String name;
    private int age;

    public Member(String name, int age) {
        this.name = name;
        this.age = age;
    }
	
	//setter和getter方法略

    @Override
    public String toString() {
        return "name='" + name + ", age=" + age + "\n";
    }

    @Override
    public int compareTo(Member member) {
        /*
            this.age:表示第一个人的年龄
            member.age:表示第二个人的年龄
         */
            return this.age - member.age;
    }
}

result:

//从小到大排列
 [name='李四7, age=19
, name='李四6, age=21
, name='张三, age=23
, name='李四1, age=24
, name='王五, age=25
, name='赵六, age=26
, name='孙七, age=27
, name='李四5, age=29
, name='李四15, age=31
, name='李四14, age=33
, name='李四9, age=34
, name='李四4, age=38
, name='李四3, age=40
, name='李四13, age=45
, name='李四8, age=51
, name='李四2, age=55
, name='李四10, age=56
, name='李四11, age=62
, name='李四12, age=72
]

Parsing output code sequence:

Sorting use age (Age), recursive minimum output data stored in the bottom of the Object array, recursion ends up layer by layer solution, known to the outermost layer, after the data is stored on the left, recursive binary tree on the right, the cycle, the data is drained ascending order (recursively to the end of the last layer recursion, one level up solution, without re-entering the same recursive).

(Picture a bit ugly)
Here Insert Picture Description

data query:

//外部类的方法
public boolean inquire(T data) {
        //判断有没有数据,,没有返回false
        if (this.size() == 0) {
            return false;
        }
        //有数据进入inquireNode()内去查找数据
        return this.root.inquireNode(data);
    }
//内部类方法
 /**
         *获取数据
         * @param data  查询的数据
         * @return 是否存在查询的数据
         */
        public boolean inquireNode(T data) {
            //判断数据是否为根节点
            if (this.data.compareTo(data) == 0) {
                return true;
            } else {
                //当数据大于根节点时(this.data < data)
                if (this.data.compareTo(data) < 0) {
                    //判断右节点有没有值
                    if (this.right != null) {
                        //递归调用去匹配值,到最后时匹配就会在判断时不满足返回false
                        return this.right.inquireNode(data);
                    } else {
                        return false;
                    }
                } else {    //当数据小于根节点时(this.data > data)
                    //判断左节点有没有值
                    if (this.left != null) {
                        //递归调用去匹配值,到最后时匹配就会在判断时不满足返回false
                        return this.left.inquireNode(data);
                    } else {
                        return false;
                    }
                }
            }
        }

Comparable和Comparator

the difference:

1. java.lang.Comparable: when the class definitions implemented interface, which has a comparTo () method is used to confirm the relationship between the size, native support for the class.
2. java.util.Comparator: belong Salvager, only a compare before JDK1.8 () method is useful in a number of ways after JDK1.8 expansion, stronger than Comparable.
3. Development remains a priority in the use Comparable.

Comparable use

1, Number subclass of class instance can be used after compareTo ().

Integer num = 1;
//num大于5返回1,小于5返回 - 1,等于5返回0
System.out.println(num.compareTo(5));	 结果: -1

2. The data sorting class achieve comparable <T (type)>.
And packaging use compareTo () the same, but the class to override the compareTo (), but not packaging.

@Override
    public int compareTo(Score score) {	//传入的类
        if (score.score > this.score) {
            return -1;
        } else if (score.score < this.score) {
            return 1;
        }
        return 0;
    }

Adding new data sorting:

public void sorts (Score[]scores){
            Score score = new Score("你好",199);
             System.out.println(score.compareTo(scores[1]));
        }

Direct data in sorted array: Arrays.sort (Array instance of the class), the low-level calls Sort the compareTo (), so that a class can not be used not implement Comparable Arrays.sort () to sort, subclass Number class implements a.

Compartor use

Class implements Compartor <T (type)> To override the compare ().

@Override
    public int compare(Score t1, Score t2) {
        if (t1.getScore() > t2.getScore()) {
            return -1;
        } else if (t1.getScore() < t2.getScore()) {
            return 1;
        }
        return 0;
    }
	·	Score score = new Score("你好",199);
		//类的子类调用compare()
        System.out.println(score.compare(scores[0],scores[1]));
        System.out.println(score.compare(score,scores[0]));

Number subclass of class also compare () method of the same.

		double douA = 9.9;
        double douB = 19.9;
        System.out.println(Double.compare(douA,douB));
Published 61 original articles · won praise 0 · Views 2197

Guess you like

Origin blog.csdn.net/sabstarb/article/details/104263255