二叉树作为数据结构中的一种,是树的一种特殊结构。
其具备许多树结构:根节点(1)、双亲节点、子节点、路经、节点的度(子的个数)、节点的权(存储数字)、叶子节点(无子节点的节点)、子树、层、树的高度(最大层数)、森林。(具体含义自行百度吧)
满二叉树:所有的叶子节点都在最后一层,而且节点的总数为个(n为树的高度),n层有
个。
完全二叉树:所有叶子节点都在最后一层或者倒数第二层,且最后一层的叶子节点在左边连续,倒数第二层的叶子节点在右边连续。
所学视频中涉及到的二叉树为链式存储二叉树(普通二叉树)、顺序存储二叉树(可转换为数组)、线索二叉树(前驱节点&后继节点)、哈夫曼树(数据压缩)、二叉搜索树(二叉查找树,二叉排序树,即BST)、平衡二叉树(AVL树)、多路查找树(B树和B+树)。
二叉树节点代码:
public class TreeNode {
//节点的权
int value;
//左儿子
TreeNode leftNode;
//右儿子
TreeNode rightNode;
public TreeNode(int value) {
this.value = value;
}
//设置左儿子
public void setLeftNode(TreeNode leftNode) {
this.leftNode = leftNode;
}
//设置右儿子
public void setRightNode(TreeNode rightNode) {
this.rightNode = rightNode;
}
//中序遍历
public void frontShow() {
System.out.print(value+" ");
if(leftNode!=null) {
leftNode.frontShow();
}
if(rightNode!=null) {
rightNode.frontShow();
}
}
//中序遍历
public void midShow() {
if(leftNode!=null) {
leftNode.midShow();
}
System.out.print(value+" ");
if(rightNode!=null) {
rightNode.midShow();
}
}
//中序遍历
public void afterShow() {
if(leftNode!=null) {
leftNode.afterShow();
}
if(rightNode!=null) {
rightNode.afterShow();
}
System.out.print(value+" ");
}
//前序查找
public TreeNode Search(int i) {
TreeNode target = null;
//对比当前节点的值
if(this.value == i) {
return this;
}
//当前节点的值不是要查找的节点
else {
//查找左儿子
if(leftNode != null) {
target = leftNode.Search(i);
}
//如果不为空,说明在左儿子中已经找到
if(target != null) {
return target;
}
//查找右儿子
if(rightNode != null) {
target = rightNode.Search(i);
}
}
return target;
}
//删除一个子树
public void delete(int i) {
TreeNode parent = this;
//判断左儿子
if(parent.leftNode !=null && parent.leftNode.value == i) {
parent.leftNode = null;
return;
}
//判断右儿子
if(parent.rightNode !=null && parent.rightNode.value == i) {
parent.rightNode = null;
return;
}
//判断并递归删除
parent = leftNode;
if(parent != null) {
parent.delete(i);
}
//判断并递归删除
parent = rightNode;
if(parent != null) {
parent.delete(i);
}
}
}
至于前序查找和后序查找,会涉及到堆栈和双亲问题,并没有写出,且这两种方法不是很完备,不讨论,基本可以把中序两个字去掉就叫查找。
链式存储二叉树代码:
public class BinaryTree {
//创建一棵二叉树
TreeNode root;
//设置根节点
public void setRoot(TreeNode root) {
this.root = root;
}
//获取根节点
public TreeNode getRoot(BinaryTree binTree) {
return binTree.root;
}
public void frontShow() {
if(root != null) {
root.frontShow();
}
}
public void midShow() {
if(root != null) {
root.midShow();
}
}
public void afterShow() {
if(root != null) {
root.afterShow();
}
}
public TreeNode Search(int i) {
return root.Search(i);
}
public void delete(int i) {
if(root.value == i) {
root = null;
}else{
root.delete(i);
}
}
}
顺序存储二叉树代码:
public class ArrayBinaryTree {
int[] data;
public ArrayBinaryTree(int[] data) {
this.data = data;
}
public void frontShow() {
frontShow(0);
}
//从某一个开始遍历,前序遍历
public void frontShow(int index) {
if(data == null || data.length == 0) {
return;
}
//先遍历当前节点的内容
System.out.println(data[index]);
//2*index+1,处理左子树
if(2*index+1<data.length) {
frontShow(2*index+1);
}
//2*index+2,处理右子树
if(2*index+2<data.length) {
frontShow(2*index+2);
}
}
}
与数组对应着看,通常情况我们只考虑完全二叉树,任何一个数组都可以看成完全二叉树,此处涉及到堆排序算法。