树的遍历----递归与非递归

package com.Tree;

import java.util.Stack;
import java.util.Queue;
import java.util.LinkedList;
/*
 * 三种递归遍历方法
 * 四种非递归遍历方法
 */
public class Traverse {
	//递归先序遍历
	public void recPreOrder(BTNode root) {
		if (root == null)
			return;
		System.out.print(root.data + " ");	
		if (root.left != null)
			recPreOrder(root.left);		
		if (root.right != null)
			recPreOrder(root.right);
	}
	
	//递归中序遍历
	public void recInOrder(BTNode root) {
		if (root == null)
			return;
		if (root.left != null)
			recInOrder(root.left);		
		System.out.print(root.data + " ");		
		if (root.right != null)
			recInOrder(root.right);
	}

	//递归后序遍历
	public void recPostOrder(BTNode root) {
		if (root == null)
			return;		
		if (root.left != null)
			recPostOrder(root.left);		
		if (root.right != null)
			recPostOrder(root.right);		
		System.out.print(root.data + " ");
	} 
	
	//非递归先序遍历
	public void staPreOrder(BTNode p) {
		Stack<BTNode> stack = new Stack<BTNode>();
		
		while (p != null || stack.empty() == false) {//p!=null是为了刚开始能进入循环;
							     //stack.empty()==false是寻到空结点时while()能继续执行
			while (p != null) {
				System.out.print(p.data + " ");
				stack.push(p);
				p = p.left;
			}
			p = stack.pop();
			p = p.right;
		}
	}
	
	//非递归中序遍历
	public void staInOrder(BTNode p) {
		Stack<BTNode> stack = new Stack<BTNode>();
		
		while (p != null || stack.empty() == false) {
			while (p != null) {
				stack.push(p);
				p = p.left;
			}
			p = stack.pop();
			System.out.print(p.data + " ");
			p = p.right;
		}
	}
	
	//非递归后续遍历
	public void staPostOrder(BTNode p) {
		Stack<BTNode> stack1 = new Stack<BTNode>();
		Stack<Integer> stack2 = new Stack<Integer>();
		int flag = 0;
		
		while (p != null || stack1.empty() == false) {
			while (p != null) {
				stack1.push(p);
				stack2.push(0);
				p = p.left;
			}
			p = stack1.pop();
			flag = stack2.pop();
			if (flag == 0) {
				stack1.push(p);
				stack2.push(1);
				p = p.right;
			}
			else {
				System.out.print(p.data + " ");
				p = null;
			}
		}
	}
	//层次遍历
	public void queLayOeder(BTNode p) {
		Queue<BTNode> queue = new LinkedList<BTNode>();
		
		if (p != null) {
			//queue.offer(p);
			//p = queue.poll();
			while (p != null) {		
				System.out.print(p.data + " ");
				if (p.left != null)
					queue.offer(p.left);
				if (p.right != null)
					queue.offer(p.right);
				p = queue.poll();
			}
		}
	}
	
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值