树结构是一种非线性储存结构,存储的是具有“一对多”关系的数据元素的集合

二叉树(Binary Tree) 是树形结构的重要类型,许多实际问题抽象出来的数据结构往往是二叉树形式,即使是一般的树也能被简单的转换为二叉树,而二叉树的存储结构及其算法是比较简单的,因此二叉树显得很重要,
二叉树的特点:每个结点最多有两颗子树,而且有左右之分
除了最后一层外,每一层上的所有结点都有两个字结点

完全二叉树,除了最后一层可能不满意外,其他各层都达到层结点的最大数,最后一层不满,该层所有结点的是靠左排
完全二叉树

非完全二叉树

二叉树的遍历




利用二叉树结构以及遍历方式可以基于二叉树的元素处理排序

/**
* 基于二叉树结构实现元素排序处理的排序器
*/
public class BinaryTreeSort<E extends Integer> {
Node<E> root;//根结点
int size;
/**
* 将元素添加到排序器中
*/
public void add (E element){
//实例化结点对象
Node<E> node = new Node<>(element);
//判断当前二叉树中是否右根结点,如果没有那么新结点则为根结点
if (this.root == null){
this.root = node;
}else {
this.root.addNode(node);
}
size++;
}
/**
* 对元素排序
*
*/
public void sort(){
if (this.root ==null){
return;
}
this.root.inorderTraversal();
}
/**
* 定义结点类
*/
public class Node<E extends Integer>{
private E item;//存放元素
private Node left; //存放的左子树
private Node right;//存放的右子树
public Node() {
}
public Node(E item) {
this.item = item;
}
/**
* 添加结点
*/
public void addNode(Node node){
//完成新结点的元素与当前结点中的元素判断
//如果新结点中的元素小于当前结点中的元素,那么新结点则放在当前结点的左子树中
if (node.item.intValue() < this.item.intValue()){
if (this.left == null)
this.left = node;
else
this.left.addNode(node);
}else {
//如果新结点中的元素大于当前结点中的元素,那么新结点则放在当前结点的右子树中
if (this.right == null)
this.right = node;
else
this.right.addNode(node);
}
}
//使用中序遍历二叉树
public void inorderTraversal(){
//先找最左侧的哪个结点
if (this.left != null){
this.left.inorderTraversal();
}
System.out.println(this.item);
if (this.right != null){
this.right.inorderTraversal();
}
}
}
}
public class TreeDemo {
public static void main(String[] args) {
BinaryTreeSort binaryTreeSort = new BinaryTreeSort();
binaryTreeSort.add(12);
binaryTreeSort.add(4);
binaryTreeSort.add(5);
System.out.println("大小:"+binaryTreeSort.size);
binaryTreeSort.sort();
}
}
