java算法(三)迭代(非递归)实现二叉树的前序中序后序遍历

递归无疑是遍历二叉树最简洁的方式,其依赖的是函数栈,非递归实现的话只要通过栈的辅助就可以了。


前序遍历:根节点首先入栈,然后栈中元素依次出栈,每次出栈时压入该元素的右孩子和左孩子(注意这个顺序,这样弹出时才是左孩子在前)

public void frontPrint(BTree tree){
		if (tree==null) {
			return;
		}
		Stack<BTree> stack=new Stack<>();
		stack.push(tree);
		BTree temp=tree;
		while(!stack.isEmpty()){
			BTree tr=stack.pop();
			System.out.print(tr.value+"  ");
			if (tr.right!=null) {
				stack.push(tr.right);
			}
			if (tr.left!=null) {
				stack.push(tr.left);
			}
		}
	}

中序遍历:依次遍历左孩子入栈,到头后弹出栈顶元素并开始处理右孩子。

public void centerPrint(BTree tree){
		if (tree==null) {
			return;
		}
		Stack<BTree> stack=new Stack<>();
		BTree temp=tree;
		while(!stack.isEmpty()||temp!=null){
			if (temp!=null) {
				stack.push(temp);
				temp=temp.left;
			} else {
				BTree bt=stack.pop();
				System.out.print(bt.value+"   ");
				temp=bt.right;
			}
		}
	}


后序遍历:要用到两个栈,根节点首先入栈1,然后栈1依次出栈,每次出栈时该元素入栈2并将左右孩子压入栈1。最后得到的栈2依次出栈就是后序遍历结果。

public void behindPrint(BTree tree){
		if (tree==null) {
			return;
		}
		Stack<BTree> stack1=new Stack<>();
		Stack<BTree> stack2=new Stack<>();
		stack1.push(tree);
		BTree temp=tree;
		while(!stack1.isEmpty()){
			BTree tr=stack1.pop();
			stack2.push(tr);
			if (tr.left!=null) {
				stack1.push(tr.left);
			}
			if (tr.right!=null) {
				stack1.push(tr.right);
			}
		}
		while (!stack2.isEmpty()) {
			System.out.print(stack2.pop().value+"  ");
		}
	}





猜你喜欢

转载自blog.csdn.net/zhang___yong/article/details/79180973
今日推荐