二叉树的前、中、后遍历递归和非递归java实现

import java.util.Stack;

class BinaryNode{
	Object element;
	BinaryNode left;
	BinaryNode right;
	public BinaryNode(Object element,BinaryNode left,BinaryNode right){
		this.element = element;
		this.left = left;
		this.right = right;
	}
}
public class SyncObject {
	//递归的前、中、后排序
	public static void pre(BinaryNode b){
		if(b==null)return;
		System.out.print(b.element);
		pre(b.left);
		pre(b.right);
	}
	public static void in(BinaryNode b){
		if(b==null)return;
		in(b.left);
		System.out.print(b.element);
		in(b.right);
	}
	public static void aft(BinaryNode b){
		if(b==null)return;
		aft(b.left);
		aft(b.right);
		System.out.print(b.element);
	}
	//非递归的前、中、后排序,需要堆栈存储信息
	public static void nPre(BinaryNode b){
		Stack<BinaryNode> stack = new Stack<BinaryNode>();
		while (b!=null||!stack.isEmpty()) {
			if(b!=null){
				System.out.print(b.element);
				stack.push(b);
				b=b.left;
			}else{
				b = stack.pop();				
				b=b.right;
			}
		}		
	}
	public static void nIn(BinaryNode b){
		Stack<BinaryNode> stack = new Stack<BinaryNode>();
		while (b!=null||!stack.isEmpty()) {
			if(b!=null){
				stack.push(b);
				b=b.left;
			}else{
				b = stack.pop();
				System.out.print(b.element);
				b=b.right;
			}
		}
	}
	
	public static void nAft(BinaryNode b){
		Stack<BinaryNode> stack = new Stack<BinaryNode>();
		Stack<BinaryNode> temp = new Stack<BinaryNode>();
		while (b!=null||!stack.isEmpty()) {
			if(b!=null){
				stack.push(b);
				temp.push(b);
				b=b.right;
			}else{
				b=stack.pop();
				b=b.left;
			}			
		}
		while (!temp.isEmpty()) {
			System.out.print(temp.pop().element);
		}		
	}
	public static void main(String[] args) throws InterruptedException, CloneNotSupportedException {
		BinaryNode dNode = new BinaryNode("D", null, null);
		BinaryNode eNode = new BinaryNode("E", null, null);
		BinaryNode fNode = new BinaryNode("F", null, null);
		BinaryNode gNode = new BinaryNode("G", null, null);
		BinaryNode bNode = new BinaryNode("B", dNode, eNode);
		BinaryNode cNode = new BinaryNode("C", fNode, gNode);
		BinaryNode root = new BinaryNode("A", bNode, cNode);
		pre(root);
		System.out.println();
		nPre(root);
		System.out.println();
		System.out.println("--------------------------------");
		in(root);
		System.out.println();
		nIn(root);
		System.out.println();
		System.out.println("--------------------------------");
		aft(root);
		System.out.println();
		nAft(root);
		
	}
	

}


                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值