public class TreeSearchUtils {
public static void boundarySearch(TreeNode<Integer> treeNode, int data) {
TreeNode<Integer> p = treeNode;
while (p != null) {
if (p.getData().intValue() == data) {
Log.d("tree", "has find");
return;
} else if (p.getData() > data) {
p = p.getLeftChild();
} else {
p = p.getRightChild();
}
}
Log.d("tree", "has not find");
}
public static void boundaryInsert(@NonNull TreeNode<Integer> tree, int data) {
TreeNode<Integer> p = tree;
if (p == null) {
tree = new TreeNode<>(data);
return;
}
while (p != null) {
if (data > p.getData()) {
if (p.getRightChild() == null) {
p.setRightChild(new TreeNode<Integer>(data));
return;
}
p = p.getRightChild();
} else {
if (p.getLeftChild() == null) {
p.setLeftChild(new TreeNode<Integer>(data));
return;
}
p = p.getLeftChild();
}
}
}
/**
* 1删除的节点没有子节点,直接删除
* 2。删除的节点有一个子节点,直接把这个节点接上去
* 3。删除的节点有左右节点,取第一个大于删除节点的数替代,右子数的最左节点
*
* @param data
*/
public static void boundaryDelete(TreeNode<Integer> treeNode, int data) {
if (treeNode == null) {
return;
}
TreeNode<Integer> p = treeNode;
TreeNode<Integer> parent = null;
while (p != null) {
if (p.getData() == data) {
// 找到当前的元素
if (p.getLeftChild() == null && p.getRightChild() == null) {
if (parent == null) {
// 单个节点的情况
treeNode = null;
} else {
if (parent.getLeftChild() != null && parent.getLeftChild().getData() == data) {
parent.setLeftChild(null);
} else if (parent.getRightChild() != null && parent.getRightChild().getData() == data) {
parent.setRightChild(null);
}
}
return;
} else if (p.getLeftChild() != null && p.getRightChild() != null) {
// 两个节点都不为空,去寻找后驱节点,右数的最左节点
TreeNode<Integer> tem = p.getRightChild();
TreeNode<Integer> pre = p;
while (tem.getLeftChild() != null) {
pre = tem;
tem = tem.getLeftChild();
}
// 替代当前的节点数据
p.setData(tem.getData());
if (pre != null) {
// 删除节点
if (pre.getRightChild().getData() == tem.getData()) {
pre.setRightChild(null);
} else {
pre.setLeftChild(null);
}
}
} else {
Log.d("tree","delte single");
if (parent == null) {
// 头节点
if (p.getLeftChild() != null) {
treeNode = p.getLeftChild();
} else {
treeNode = p.getRightChild();
}
} else {
if (p.getLeftChild() != null) {
parent.setLeftChild(p.getLeftChild());
} else {
parent.setRightChild(p.getRightChild());
}
}
}
return;
} else if (data > p.getData()) {
parent = p;
p = p.getRightChild();
} else {
parent = p;
p = p.getLeftChild();
}
}
}
}