二叉树特点
左节点值小于根节点值,右节点值大于根节点
public class BinaryTree {
private Node root;
@Data
private static class Node {
private int data;
private Node left;
private Node right;
public Node(int data){
this.data = data;
}
}
public Node find(int key){
Node current = root;
while(current != null){
if(current.data > key){
current = current.left;
}
if(current.data < key){
current = current.right;
}
if(current.data == key){
return current;
}
}
return null;
}
public boolean insert(int data){
Node newNode = new Node(data);
if(root == null){
root = newNode;
return true;
}else{
Node current = root;
Node parent = null;
while (current != null){
parent = current;
if(current.data > data){
current = current.left;
if(current == null){
parent.left = newNode;
return true;
}
} else{
current = current.right;
if(current == null){
parent.right = newNode;
return true;
}
}
}
}
return false;
}
public Node findMax(){
Node current = root;
while(current != null){
current = current.right;
}
return current;
}
public Node findMin(){
Node current = root;
while (current != null) {
current = current.left;
}
return current;
}
//删除没有子节点的节点
public boolean delete(int key){
Node current = root;
Node parent = current;
boolean isLeft = false;
while (current.data != key){
parent = current;
if(current.data > key){
isLeft = true;
current = current.left;
}else {
isLeft = false;
current = current.right;
}
if(current == null){
return false;
}
}
if(current.left == null && current.right == null){
if(current == root){
root = null;
}
if(isLeft){
parent.left = null;
}else{
parent.right = null;
}
return true;
}
return false;
}
}