java非递归实现二叉树的遍历

1、二叉树先序非递归遍历思想

        <1>初始化设置一个堆栈;

   <2>把根节点指针入栈;

   <3>当栈非空时,循环执行步骤3-1到步骤3-3

      3-1:出栈取得栈顶节点,访问该节点;

      3-2:若该节点的右孩子节点非空,则将该节点的右孩子节点指针入栈;

      3-3:若该节点的左孩子节点非空,则将该节点的左孩子节点指针入栈;

   <4>算法结束

2、中序非递归遍历思想

    <1> 初始化栈,根节点入栈

  <2> 若栈非空,则栈顶节点的左孩子依次进栈。直到null,则<3>

  <3> 访问栈顶节点,使栈顶节点出栈。若栈顶节点右孩子非空,则使右孩子进栈成为栈顶节点。重复<2>至栈空。


初始化二叉树如图所示:


步骤如下:



至此,中序输出顺序为:D->B->H->E->I->A->F->C->G

程序代码如下:

public class BinaryNode<E> {
	public E data;
	public BinaryNode<E> left,right;
	
	public BinaryNode(E data,BinaryNode<E> left,BinaryNode<E> right){
		this.data = data;
		this.left = left;
		this.right = right;
	}
	
	public BinaryNode(E data){
		this(data,null,null);
	}
	
	public BinaryNode(){
		this(null,null,null);
	}
	
	public boolean isLeaf(){
		return this.left == null && this.right == null;
	}
	
	public String toString(){
		return this.data.toString();
	}
}
public class LinkedStack<E> implements SStack<E> {

	private Node<E> top;
	
	public LinkedStack(){
		this.top = null;
	}
	
	public boolean isEmpty() {
		return this.top == null;
	}

	public boolean push(E element) {
		if(element == null){
			return false;
		}
		this.top = new Node(element,this.top);
		return true;
	}

	public E pop() {
		if(!isEmpty()){
			E temp = this.top.data;
			this.top = this.top.next;
			return temp;
		}
		return null;
	}

	public E get() {
		if(!isEmpty()){
			return this.top.data;
		}
		return null;
	}

}
public class BinaryTree<E> {
	protected BinaryNode<E> root;
	
	public BinaryTree(){
		root = null;
	}
	
	public BinaryTree(BinaryNode<E> root){
		this.root = root;
	}
	
	
	/**
	 * 中序非递归遍历
	 */
	public void  nonRecInorder(){
		System.out.println("中根次序非递归遍历:");
		LinkedStack<BinaryNode<E>> stack = new LinkedStack<BinaryNode<E>>();
		BinaryNode<E> p = this.root;
		while(p != null || !stack.isEmpty()){
			if(p != null){
				stack.push(p);
				p = p.left;
			}else{
				p = stack.pop();
				System.out.println(p.data + " ");
				p = p.right;
			}
			System.out.println();
		}
	}
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值