代码拉取完成,页面将自动刷新
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;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。