1 Star 0 Fork 40

SE-201/lec05-tree

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
BinaryTree.java 2.65 KB
一键复制 编辑 原始数据 按行查看 历史
import java.util.Queue;
import java.util.LinkedList;
public class BinaryTree<T extends Comparable<T>> {
public Node root;
BinaryTree(){
root = null;
}
/*
* 10
* 5 15
* 3 7 12 20
*
* preOrder: 10 5 3 7 15 12 20
*/
public void preOrderTraversal(){
preOrder(root);
}
public void preOrder(Node tree){
if(tree != null ){
System.out.print(tree.value);
System.out.print(" ");
preOrder(tree.left);
preOrder(tree.right);
}
}
public void inOrder(){}
public void postOrder(){}
public void levelOrder(){}
public void insert(T val){
Node<T> newNode = new Node(val);
Node<T> temp = root;
if(root == null){
root = newNode;
return;
}
while(temp != null){
if(val.compareTo(temp.value) < 0){
if(temp.left != null){
temp = temp.left;
} else {
temp.left = newNode;
break;
}
} else if(val.compareTo(temp.value) == 0){
break;
}
else {
if(temp.right != null){
temp = temp.right;
} else {
temp.right = newNode;
break;
}
}
}
}
public void delete(T val){
if(root == null){
return;
}
// 1. 找到被删的节点及其父节点
Node<T> parent = root;
Node<T> current = root;
while(current != null){
if(val.compareTo(current.value) == 0){
break;
} else if(val.compareTo(current.value) < 0){
parent = current;
current = current.left;
} else {
parent = current;
current = current.right;
}
}
// while结束后:1. 找到了 current !=null 2. 没找到 current == null
// 2. 删除3种情况
if(current != null){
// 2.1 leaf, 0 child
if(current.left == null && current.right == null){
if(current == root){
root = null;
} else {
if(parent.left == current){
parent.left = null;
} else {
parent.right = null;
}
}
}
// 2.2 1 child
else if (current.left == null || current.right == null){
}
// 2.3 2 children
else {
T maxValue = findMaxAndDelete(current, current.left);
current.value = maxValue;
}
}
}
private T findMaxAndDelete(Node beReplaced, Node root){
Node<T> parent = beReplaced;
Node<T> current = root;
while(current != null && current.right != null){
parent = current;
current = current.right;
}
// while结束后, current是当前root树的最大值
if(current.left != null){
if(parent.left == current){
parent.left = current.left;
} else {
parent.right = current.left;
}
} else {
parent.right = null;
}
return current.value;
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/se201/lec05-tree.git
git@gitee.com:se201/lec05-tree.git
se201
lec05-tree
lec05-tree
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385