非递归方式遍历树(先序,中序,后序)

import java.util.Stack;
import java.util.concurrent.LinkedBlockingDeque;

public class TreeTraversal {

	public Node createTree() throws InterruptedException{
		LinkedBlockingDeque<Node> queue = new LinkedBlockingDeque<Node>();
		Node root = new Node();
		int idx = 0;
		root.setData(idx);
		queue.add(root);
		while(true){
			if(queue.isEmpty())break;
			Node curr = queue.pop();
			
			idx++;
			Node left = new Node();
			left.setData(idx);
			curr.setLeft(left);
			
			Node right = new Node();
			idx++;
			right.setData(idx);
			
			curr.setRight(right);
			queue.putLast(left);
			queue.putLast(right);
			System.out.println("curr="+curr.getData()
					+" left="+curr.getLeft().getData()
					+" right="+curr.getRight().getData());
			if(idx>10)break;
		}
		return root;
	}
	
	public void rootPrivilege(Node root) throws InterruptedException{
		LinkedBlockingDeque<Node> queue = new LinkedBlockingDeque<Node>();
		queue.putLast(root);
		while(true){
			if(queue.isEmpty())break;
			Node node = queue.pop();
			System.out.println(node.getData());
			if(node.getLeft()!=null)queue.putLast(node.getLeft());
			if(node.getRight()!=null)queue.putLast(node.getRight());
		}
	}
	public void rootLast(Node root) throws InterruptedException{
		Stack<Node> stack = new Stack<Node>();
		stack.push(root);
		LinkedBlockingDeque<Node> queue = new LinkedBlockingDeque<Node>();
		while(true){
			if(stack.isEmpty())break;
			Node curr = stack.pop();
			queue.putFirst(curr);
			if(curr.getLeft()!=null)stack.push(curr.getLeft());
			if(curr.getRight()!=null)stack.push(curr.getRight());
		}
		while(!queue.isEmpty()){
			System.out.println(queue.pop().getData());
		}
	}
	private void rootMiddleLeftTillEnd(Stack<Node> stack, Node curr){
		stack.push(curr);
		while(curr.getLeft()!=null){
			stack.push(curr.getLeft());
			curr = curr.getLeft();
		}
	}
	public void rootMiddle(Node root) throws InterruptedException{
		Stack<Node> stack = new Stack<Node>();
		
		rootMiddleLeftTillEnd(stack, root);
		while(true){
			if(stack.isEmpty())break;
			Node curr = stack.pop();
			System.out.println(curr.getData());
			if(curr.getRight()!=null)rootMiddleLeftTillEnd(stack, curr.getRight());
		}
	}
	public static void main(String args[]){
		TreeTraversal t = new TreeTraversal();
		try {
			Node root = t.createTree();
			t.rootMiddle(root);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值