10.10树的遍历

public class Main {
public static void main(String[] args) {
trees<Integer> t=new trees<>(1);
trees<Integer> t1=new trees<>(2);
trees<Integer> t2=new trees<>(3);
trees<Integer> t3=new trees<>(4);
trees<Integer> t4=new trees<>(5);
t.left=t1;
t.right=t2;
t1.left=t3;
t1.right=t4;
System.out.println("前序");
t.preOrder(t);
System.out.println();
System.out.println("中序");
t.midOrder(t);
System.out.println();
System.out.println("后序");
t.lastOrder(t);
t.preOrderandmidOrder(t);
t.floorOrder(t);

}
}
 
 
 
import java.util.LinkedList;
import java.util.Stack;
public class trees<T> {
private T data;
public trees<T> left;
public trees<T> right;

public trees(T data) {
this.data = data;
this.left = null;
this.right = null;
}

public trees(T data, trees<T> left, trees<T> right) {
this.data = data;
this.left = left;
this.right = right;
}

public void preOrder(trees<T> t) {//递归前序
if (t != null) {
System.out.print(t.data+" ");
preOrder(t.left);
preOrder(t.right);
}
}

public void preOrderandmidOrder(trees<T> t) {//非递归前序和中序
trees<T> current = t;
LinkedList<T> pre = new LinkedList<>();
LinkedList<T> mid = new LinkedList<>();
Stack<trees> S = new Stack<>();
while (current != null || !S.isEmpty()) {
if (current != null) {
S.push(current);
pre.add(current.data);
current = current.left;
} else {
trees<T> pop=S.pop();
mid.add(pop.data);
current = pop.right;

}
}
System.out.println();
System.out.println("前序");
for(T pre1:pre)
{
System.out.print(pre1+" ");
}
System.out.println();
System.out.println("中序");
mid.forEach(data-> System.out.printf(data+" "));
}
 
public void lastOrder1(trees<T> t) {//非递归后序
trees<T> current = t;
trees<T> pop = null;
LinkedList<T> last = new LinkedList<>();
Stack<trees> S = new Stack<>();
while (current != null || !S.isEmpty()) {
if (current != null) {
S.push(current);
current = current.left;
} else {
trees<T> peek=S.peek();
if(peek.right==null||peek.right==pop)
{
pop=S.pop();
last.add(pop.data);
}
else
{
current=peek.right;
}

}
}
System.out.println();
System.out.println("后序");
for(T last1:last)
{
System.out.print(last1+" ");
}
}
 
 
public void floorOrder(trees<T> t)//层序遍历
{
System.out.println("层序遍历");
ArrayDeque<trees> A=new ArrayDeque<>();
while(t!=null)
{
System.out.print(t.data+" ");
if(t.left!=null)
{
A.add(t.left);
}
if(t.right!=null)
{
A.add(t.right);
}
t=A.poll();
}
}
 

public void midOrder(trees<T> t) {//递归中序
if (t != null) {
midOrder(t.left);
System.out.print(t.data+" ");
midOrder(t.right);
}
}

public void lastOrder(trees<T> t) {//递归后序
if (t != null) {
lastOrder(t.left);
lastOrder(t.right);
System.out.print(t.data+" ");
}
}
}
posted @ 2023-10-10 21:43  赵千万  阅读(4)  评论(0编辑  收藏  举报