二叉树非递归遍历Java实现

二叉树的前序、中序和后序遍历可以采用递归和非递归的方法实现,递归的方法逻辑简单清晰,易于理解,但递归的方法需要使用额外的栈空间,运行效率较低。而非递归的方法则效率较高。


维基百科上有递归和非递归二叉树三种遍历实现的伪代码,https://en.wikipedia.org/wiki/Tree_traversal#In-order_2

下面是相应的Java实现:


前序遍历(非递归实现):

public static void preOrder(TreeNode x)
	{
		System.out.println();
		if(x!=null)
		{
			LinkedList<TreeNode> stack=new LinkedList<TreeNode>();
			
			stack.addLast(x);
			while(!stack.isEmpty())
			{
				TreeNode temp=stack.removeLast();
				System.out.print(temp.val+" ");
				
				if(temp.rchild!=null)
				{
					stack.addLast(temp.rchild);
				}
				
				if(temp.lchild!=null)
				{
					stack.addLast(temp.lchild);	
				}
				
			}
			System.out.println();
		}
	}



中序遍历(非递归实现):

public static void inOrder(TreeNode x)
	{
		System.out.println();
		if(x!=null)
		{
			LinkedList<TreeNode> stack=new LinkedList<TreeNode>();

			while(!stack.isEmpty()||x!=null)
			{
				if(x!=null)
				{
					stack.addLast(x);
					x=x.lchild;
				}
				else
				{
					x=stack.removeLast();
					System.out.print(x.val+" ");
					x=x.rchild;
				}
			}
			System.out.println();
		}
	}
	



后序遍历(非递归实现):

public static void postOrderII(TreeNode x)
	{
		LinkedList<TreeNode> stack=new LinkedList<TreeNode>();
		TreeNode lastNodeVistited=null;
		while(!stack.isEmpty()||x!=null)
		{
			if(x!=null)
			{
				stack.addLast(x);
				x=x.lchild;
			}
			else
			{
				TreeNode top=stack.getLast();
				if(top.rchild!=null&&lastNodeVistited!=top.rchild)
				{
					x=top.rchild;
				}
				else
				{
					System.out.print(top.val+" ");
					lastNodeVistited=stack.removeLast();
				}
			}
		}
		System.out.println();
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值