1.定义一个二叉树其实很容易。
1.1 节点
对于任意节点都存在两个子节点,分别是左节点和右节点
public class TreePoint<T> {
public TreePoint(){
}
public TreePoint(T value){
this.value = value;
}
TreePoint leftPoint;
TreePoint rightPoint;
T value;
public TreePoint getLeftPoint() {
return leftPoint;
}
public void setLeftPoint(TreePoint leftPoint) {
this.leftPoint = leftPoint;
}
public TreePoint getRightPoint() {
return rightPoint;
}
public void setRightPoint(TreePoint rightPoint) {
this.rightPoint = rightPoint;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}
让这个节点以某种形式组成一个存在二叉的树,那就是二叉树了。
public class TreeController<T> {
public TreePoint<T> origin;
public TreeController(){
}
public static final int left = 0;
public static final int right = 764;
//非递归
public void addPoint(T value,int dir){
if (origin == null){
origin = new TreePoint<>(value);
return;
}
TreePoint selectPoint = origin;
switch (dir){
case left:
while (selectPoint.leftPoint!= null){
selectPoint = selectPoint.leftPoint;
}
break;
case right:
while (selectPoint.rightPoint!= null){
selectPoint = selectPoint.rightPoint;
}
break;
default:
break;
}
switch (dir){
case left:
selectPoint.setLeftPoint(new TreePoint(value));
break;
case right:
selectPoint.setRightPoint(new TreePoint(value));
break;
default:
break;
}
}
public void operation(T value){
System.out.println(value);
}
//遍历
public void tranverse(TreePoint<T> point){
operation(point.value);
if (point.leftPoint != null){
tranverse(point.leftPoint);
}
if (point.rightPoint!= null){
tranverse(point.rightPoint);
}
}
}
当我去使用这个二叉树时,其实就很方便:
当我们遍历输出后,其结果如下:
以上,应该算一个最简单的二叉树的行成。但是二叉树存在的意义,其实才刚刚开始。