package com.wy.tree;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class BST {
//树的根节点
private static Treeroot root;
//树的结构
private static class Treeroot{
private String val;
private Treeroot left,right;
public Treeroot(String val,Treeroot left,Treeroot right) {
this.val = val;
this.left = left;
this.right = right;
}
}
//递归先序遍历
public static void preOrderRec(Treeroot root){
if(root!=null){
System.out.print(root.val+" ");
preOrderRec(root.left);
preOrderRec(root.right);
}
}
//非递归先序遍历
public static void preOrderRec2(Treeroot root){
Stack<Treeroot> stack = new Stack<Treeroot>();
if(root!=null){
stack.push(root);
while(!stack.isEmpty()) {
root = stack.pop();
System.out.print( root.val+" " );
if(root.right!=null)
stack.push(root.right);
if(root.left!=null)
stack.push( root.left );
}
}
}
//递归中序遍历
public static void inOrderRec(Treeroot root){
if(root!=null){
inOrderRec(root.left);
System.out.print(root.val+" ");
inOrderRec(root.right);
}
}
//非递归中序遍历
public static void inOrderRec2(Treeroot root){
Stack<Treeroot> stack = new Stack<Treeroot>();
while(root!=null || !stack.isEmpty()){
while(root!=null){
stack.push(root);//先访问再入栈
root=root.left;
}
root=stack.pop();
System.out.print(root.val+" ");
root=root.right;//如果是null,出栈并处理右子树
}
}
//递归后序遍历
public static void postOrderRec(Treeroot root){
if(root!=null){
postOrderRec(root.left);
postOrderRec(root.right);
System.out.print(root.val+" ");
}
}
//非递归后序遍历
public static void postOrderRec2(Treeroot root){
Stack<Treeroot> stack = new Stack<Treeroot>();
Treeroot pre = root;
while(root!=null){
while(root.left!=null){
stack.push(root);
root = root.left;
}
while(root!=null && (root.right==null || root.right==pre)){
System.out.print(root.val+" ");
pre = root;
if(stack.isEmpty()) return;
root = stack.pop();
}
stack.push(root);
root = root.right;
}
}
public static void ceng(Treeroot root) {
Queue<Treeroot> queue = new LinkedList<Treeroot>();
queue.offer(root);
while(!queue.isEmpty()) {
root = queue.poll();
System.out.print( root.val+" " );
if(root.left!=null)
queue.offer(root.left);
if(root.right!=null)
queue.offer(root.right);
}
}
public static void main(String[] args) {
//创建树
Treeroot x = new Treeroot("x",null,null);
Treeroot y = new Treeroot("y",null,null);
Treeroot d = new Treeroot("d",x,y);
Treeroot e = new Treeroot("e",null,null);
Treeroot f = new Treeroot("f",null,null);
Treeroot c = new Treeroot("c",e,f);
Treeroot b = new Treeroot("b",d,null);
Treeroot a = new Treeroot("a",b,c);
root = a;
// BST.preOrderRec(root); //递归先序遍历
// System.out.println();
// BST.preOrderRec2(root); //非递归先序遍历
// System.out.println();
// BST.inOrderRec(root); //递归中序遍历
// System.out.println();
// BST.inOrderRec2(root); //非递归中序遍历
// System.out.println();
BST.postOrderRec(root); //递归后序遍历
System.out.println();
BST.postOrderRec2(root);
System.out.println();
BST.ceng(root); //层次遍历
}
}
Java实现二叉树的遍历
最新推荐文章于 2021-03-06 10:42:51 发布

488

被折叠的 条评论
为什么被折叠?



