各个数据结构的优缺点
数组结构
查找快,删除插入慢。
链表结构
删除插入块,查找慢。
树形结构
综合了链表和数组的优缺点。
二叉树简介
- 每个节点最多只能有2个子节点的一种形式称为二叉树。
- 二叉树的子节点分为左节点和右节点。
- 如果叶子节点都在最后一层叫做满二叉树
- 如果二叉树的叶子节点在最后一层或倒数第二层,而且最后一层的叶子节点在左边连续,倒数第二层的叶子节点右边连续,我们称为完全二叉树
二叉树遍历
前序遍历
先输出父节点,然后输出父节点的左节点,最后是右节点。(中左右)
public static void preOrder(BinaryTreeNode root) {
if (root == null) return;
System.out.println(root.value);
preOrder(root.left);
preOrder(root.right);
}
中序遍历
先输出父节点的左节点,然后输出父节点,最后是右节点。(左中右)
public static void inOrder(BinaryTreeNode root) {
if (root == null) return;
inOrder(root.left);
System.out.println(root.value);
inOrder(root.right);
}
后序遍历
先输出父节点的左节点,然后输出右节点,最后是父节点。(左右中)
public static void postOrder(BinaryTreeNode root) {
if (root == null) return;
postOrder(root.left);
postOrder(root.right);
System.out.println(root.value);
}
二叉树查找
查找二叉树中的某个值。
public static BinaryTreeNode preSearch(BinaryTreeNode root, int value) {
if (root == null) return null;
if (value == root.value) {
return root;
}
BinaryTreeNode left = preSearch(root.left, value);
BinaryTreeNode right = preSearch(root.right, value);
//递归向上传递
if (left != null) {
return left;
} else if (right != null) {
return right;
}
return null;
}
二叉树节点的删除
关键点是找到要删除节点的父节点,将子节点设置为null。
public static BinaryTreeNode delete(BinaryTreeNode root, int value) {
if (root == null) return null;
if (value == root.value) {
return root;
}
BinaryTreeNode left = delete(root.left, value);
BinaryTreeNode right = delete(root.right, value);
//删除节点
if (left != null) {
root.left = null;
return null;
} else if (right != null) {
root.right = null;
return null;
}
return null;
}