\
1. 二叉树定义
树的遍历是树的一种重要的运算。所谓遍历是指对树中所有结点的信息的访问,即依次对树中每个结点访问一次且仅访问一次。,一般情况下树的遍历有四种情况,而对二叉树来说有四种情况,这里主要阐述三种情况。我们用一个树结构来举例子。
- 先序遍历 所谓先序遍历,也就是前序遍历,是从根节点开始,在左,在右,不断递归,该树的前序遍历为: ABCDEFGHIJ
- 中序遍历 中序遍历,从左节点开始,在根,在右。遍历为: CBDEAFHGIJ
- 后序遍历 从左节点开始,在右,在根,遍历为: CDEBFHIJGA
2. 小根堆和大根堆
-
Min-heap: 父节点的值小于或等于子节点的值;
-
Max-heap: 父节点的值大于或等于子节点的值;
public class HeapManager { private Queue<Integer> minHeap = new PriorityQueue<>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1 - o2; } }); private Queue<Integer> maxHeap = new PriorityQueue<>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2 - o1; } }); public void test(){ int[] arrForHeap = { 3, 5, 2, 7, 0, 1, 6, 4 }; for(int data:arrForHeap){ minHeap.offer(data); maxHeap.offer(data); } System.out.println("print the minHeap:"); while (!minHeap.isEmpty()){ System.out.print(" "+minHeap.poll()); } System.out.println(); System.out.println("print the maxHeap:"); while (!maxHeap.isEmpty()){ System.out.print(" "+maxHeap.poll()); } } }
打印结果:
print the minHeap: 0 1 2 3 4 5 6 7 print the maxHeap: 7 6 5 4 3 2 1 0 Process finished with exit code 0
3. 二分搜索树
一、概念及其介绍
二分搜索树(英语:Binary Search Tree),也称为 二叉查找树 、二叉搜索树 、有序二叉树或排序二叉树。满足以下几个条件:
- 若它的左子树不为空,左子树上所有节点的值都小于它的根节点。
- 若它的右子树不为空,右子树上所有的节点的值都大于它的根节点。
- 它的左、右子树也都是二分搜索树。