一个二叉搜索树的简单实现
package com.tree;
import java.util.ArrayList;
import java.util.List;
/**
* @Description 二叉搜索树
* @Author xsl
* @Date 2020/6/26 18:09
**/
public class MyTree<T> {
/**
* 数据域
*/
private T data;
/**
* 左子树
*/
private MyTree leftTree;
/**
* 右子树
*/
private MyTree rightTree;
/**
* 添加一个结点
* @param data
* @return
*/
public void add(T data) {
if (data == null) {
return ;
}
//该结点数据为空或者该节点数据与插入结点值相等
if (this.data == null || this.data.equals(data)) {
this.data = data;
} else {
if (data.hashCode() < this.data.hashCode()) {
//小于
if (null == leftTree) {
//左子树为空构建新节点
leftTree = new MyTree(data);
} else {
//左子树不为空,递归
leftTree.add(data);
}
}else {
//大于
if (null == rightTree){
//右子树为空构建新节点
rightTree = new MyTree(data);
}else {
//右子树已有值,递归
rightTree.add(data);
}
}
}
}
/**
* 中序遍历
* @return
*/
public List<Object> inorderTraversal(){
List<Object> values = new ArrayList<>();
if (null != leftTree){
values.addAll(leftTree.inorderTraversal());
}
values.add(data);
if (null != rightTree){
values.addAll(rightTree.inorderTraversal());
}
return values;
}
/**
* 先序
*/
public List<Object> preTraversal(){
List<Object> values = new ArrayList<>();
values.add(data);
if (null != leftTree){
values.addAll(leftTree.preTraversal());
}
if (null != rightTree){
values.addAll(rightTree.preTraversal());
}
return values;
}
/**
* 后序
*/
public List<Object> poorerTraversal(){
List<Object> values = new ArrayList<>();
if (null != leftTree){
values.addAll(leftTree.poorerTraversal());
}
if (null != rightTree){
values.addAll(rightTree.poorerTraversal());
}
values.add(data);
return values;
}
public MyTree() {
}
public MyTree(T data) {
this.data = data;
}
public T getData() {
return data;
}
private void setData(T data) {
this.data = data;
}
public MyTree getLeftTree() {
return leftTree;
}
private void setLeftTree(MyTree leftTree) {
this.leftTree = leftTree;
}
public MyTree getRightTree() {
return rightTree;
}
private void setRightTree(MyTree rightTree) {
this.rightTree = rightTree;
}
public static void main(String[] args) {
MyTree<Integer> myTree = new MyTree<>(10);
myTree.add(20);
myTree.add(5);
myTree.add(7);
myTree.add(6);
List<Object> values = myTree.poorerTraversal();
values.stream().forEach(System.out::println);
}
}