java实现的二叉树.
package tree;
import lombok.Data;
@Data
public class Node implements Tree {
private Node root = this;
private Integer data;
private Node left;
private Node right;
private Boolean isDelete;
public Node(Integer data) {
this.data = data;
}
public Node() {
}
public Node(Integer data, Node left, Node right) {
this.data = data;
this.left = left;
this.right = right;
}
//打印节点内容
public void display() {
System.out.println(data);
}
//遍历树--中序遍历
public void midEach(Node node) {
if (node == null) {
System.out.println("空树");
}
if (node.left != null) {
midEach(node.left);
}
System.out.print(node.data + " ");//中序遍历
if (node.right != null) {
midEach(node.right);
}
}
//前序遍历
public void preEach(Node node) {
if (node == null) {
System.out.println("空树");
}
System.out.print(node.data + " ");//前序遍历
if (node.left != null) {
preEach(node.left);
}
if (node.right != null) {
preEach(node.right);
}
}
//后序遍历
public void postEach(Node node) {
if (node == null) {
System.out.println("空树");
}
if (node.left != null) {
postEach(node.left);
}
if (node.right != null) {
postEach(node.right);
}
System.out.print(node.data + " ");//后序遍历
}
@Override
public Node find(Integer key) {
Node current = this.root;
while (current != null) {
if (current.data > key) {
current = current.left;
} else if (current.data < key) {
current = current.right;
} else {
return current;
}
}
//遍历完整个树没找到,返回null.
return null;
}
@Override
public boolean insert(Integer key) {
Node node = new Node(key);
if (this.root == null) {
this.root = node;
return true;
} else {
Node current = root;
Node parent;
while (current != null) {
parent = current;
if (current.data > key) {
current = current.left;
if (current == null) {
parent.left = node;
return true;
}
} else {
current = current.right;
if (current == null) {
parent.right = node;
return true;
}
}
}
}
return false;
}
@Override
public boolean delete(Integer key) {
//这里的删除比较复杂,可以用一个Boolean标签记录是否被删除.而不用破坏树的结构
return false;
}
}