1. 二叉搜索树
1.1 二叉搜索树概念
若左子树不为空,则左子树上所有节点的值都小于根节点的值
若右子树不为空,则右子树上所有节点的值都大于根节点的值
如果中序遍历( 左根右 ),结果从小到大有序。所以,二叉搜索树也叫二叉排序树
1.2 二叉搜索树的实现
class BinarySearchTree {
static class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
public TreeNode root;
// 查找
public boolean search(int val) {
TreeNode cur = root;
while (cur != null) {
if (val == cur.val) {
return true;
}else if (val < cur.val) {
cur = cur.left;
}else {
cur = cur.right;
}
}
return false;
}
// 插入
public void insert(int val) {
TreeNode node = new TreeNode(val);
if (root == null) {
root = node;
return;
}
// 先让cur走到null
TreeNode cur = root;
TreeNode prev = null;
while (cur != null) {
if (val > cur.val) {
prev = cur;
cur = cur.right;
}else if (val < cur.val){
prev = cur;
cur = cur.left;
}else {
return;
}
}
// 插入
if (val > prev.val) {
prev.right = node;
}else {
prev.left = node;
}
}
// 删除节点
public void remove(int val) {
TreeNode cur = root;
TreeNode prev = root;
while (cur != null) {
if (val > cur.val) {
prev = cur;
cur = cur.right;
} else if (val < cur.val) {
prev = cur;
cur = cur.left;
} else {
removeNode(prev,cur);
return;
}
}
}
private void removeNode(TreeNode parent,TreeNode cur) {
if (cur.left == null) {
if (cur == root) {
root = cur.right;
} else if (cur == parent.left) {
parent.left = cur.right;
}else {
parent.right = cur.right;
}
} else if (cur.right == null) {
if (cur == root) {
root = cur.left;
}else if (cur == parent.left) {
parent.left = cur.left;
}else {
parent.right = cur.left;
}
} else {
TreeNode cp = cur;
TreeNode c = cur.right;
while (c.left != null) {
cp = c;
c = c.left;
}
cur.val = c.val;
if (cp.left == c) {
cp.left = c.right;
}else {
cp.right = c.right;
}
}
}
}
class Test {
public static void main(String[] args) {
BinarySearchTree binarySearchTree = new BinarySearchTree();
binarySearchTree.insert(10);
binarySearchTree.insert(7);
binarySearchTree.insert(15);
binarySearchTree.insert(3);
binarySearchTree.insert(20);
binarySearchTree.insert(16);
binarySearchTree.insert(12);
binarySearchTree.remove(15);
}
}
删除思路 分三种情况:
1. 删除节点左边为空
2. 删除节点右边为空
3. 删除节点左右都不为空
有2中删除思路 下面实现第二种
这里需要注意
标签:right,TreeNode,cur,val,else,搜索,left From: https://www.cnblogs.com/xumu7/p/18103795