递归无疑是遍历二叉树最简洁的方式,其依赖的是函数栈,非递归实现的话只要通过栈的辅助就可以了。
前序遍历:根节点首先入栈,然后栈中元素依次出栈,每次出栈时压入该元素的右孩子和左孩子(注意这个顺序,这样弹出时才是左孩子在前)
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; } } }
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+" "); } }