package JavaStudy;
//完整版的二叉树,包括节点类,树类
/*
节点类:
节点的属性(数据,左右节点),方法:Setter和Getter方法,4种遍历方法
树类:
树类的属性:根节点
树类的方法:构造方法,4种遍历方法,和遍历数组建立二叉树的快速方法.
*/
import javax.xml.validation.SchemaFactoryConfigurationError;
import java.util.LinkedList;
import java.util.Queue;
public class 完整版的二叉树 {
public static void main(String[] args) {
int []test = {1,2,3,4,5,6,7,};
Tree2 test_tree = new Tree2(test);
test_tree.levelOrder();
test_tree.preOrder();
test_tree.infixOrder();
test_tree.postOrder();
}
}
class Node2{
int data;
Node2 left = null;
Node2 right = null;
//然后是构造方法
Node2(int data){
this.data = data;
}
//Setter,Getter方法
public void setData(int new_data){
this.data = new_data;
}
public int getData(){
return this.data;
}
public void setLeft(Node2 new_left){
left = new_left;
}
public Node2 getLeft(){
return left;
}
public void setRight(Node2 new_right){
right = new_right;
}
public Node2 getRight(){
return right;
}
@Override
public String toString(){
return "data :" + this.data;
}
//然后是4种遍历方法,记得在遍历前改写一下toString方法
public void preOrder(){
System.out.println(this);
if(left != null){
left.preOrder();
}
if(right != null){
right.preOrder();
}
}
public void infixOrder(){
if(left != null){
left.infixOrder();
}
System.out.println(this);
if(right != null){
right.infixOrder();
}
}
public void postOrder(){
if(left != null){
left.postOrder();
}
if(right != null){
right.postOrder();
}
System.out.println(this);
}
public void levelOrder(){
Queue<Node2> queue = new LinkedList<>();
queue.offer(this);
while(!queue.isEmpty()){
Node2 temp = queue.poll();
System.out.println("data :" + temp.data);
if(temp.left != null){
queue.offer(temp.left);
}
if(temp.right != null){
queue.offer(temp.right);
}
}
}
}
//然后就是树类
class Tree2{
Node2 root = null;
Tree2(){//如果是无参数构造器,那么初始化root的节点就为null;
root = null;
}
static int size = 0;
Tree2(int[] c){ //如果是有数组作为参数的构造方法的话(遍历数组建立一个二叉树)
root = creatNode2(c,0);//因为是直接在类中的方法,所以可以直接使用creatNode2
}//实际上是对根节点的初始化:对比无参数的构造方法
//然后是从前序遍历的方式建立一个二叉树,这个方法需要和构造方法以及节点类的creatNode方法进行联动
//和遍历类似,在树类中的creat其实也只是调用root属性的creat
//遍历也是,只是调用root的节点类中的遍历方法
public Node2 creatNode2(int list[],int index) {
if(index >= list.length){
return null;
}
Node2 temp = new Node2(list[index]);
temp.left = creatNode2(list,index * 2 + 1);
temp.right = creatNode2(list,index * 2 + 2);
return temp; //返回的其实是一个地址
}
//然后还有四种方法来遍历:其实就是分别调用root的四种遍历方法
public void preOrder(){
System.out.println("这是前序遍历");
if(root != null){
root.preOrder();
}
}
public void infixOrder(){
System.out.println("这是中序遍历");
if(root != null){
root.infixOrder();
}
}
public void postOrder(){
System.out.println("这是后续遍历");
if(root != null){
root.postOrder();
}
}
public void levelOrder(){
System.out.println("这是层序遍历");
if(root != null){
root.levelOrder();
}
}
}