今天复习到数据结构中的二叉树,就把二叉树的遍历(非递归) 实现了一下,感觉记录下来还是很必要的,希望每天能进步一点点。
二叉树遍历:
前序遍历:根左右(栈实现);
中序遍历:左根右(栈实现);
后序遍历:左右根(栈实现);
层次遍历:从上往下遍历(队列实现);
首先,先定义一个二叉树。
//树节点
public class BinaryTreeNode {
private int element;
private BinaryTreeNode left;
private BinaryTreeNode right;
public BinaryTreeNode(int element) {
//super();
this.element = element;
}
public BinaryTreeNode(int element, BinaryTreeNode left, BinaryTreeNode right) {
//super();
this.element = element;
this.left = left;
this.right = right;
}
public int getElement() {
return element;
}
public void setElement(int element) {
this.element = element;
}
public BinaryTreeNode getLeft() {
return left;
}
public void setLeft(BinaryTreeNode left) {
this.left = left;
}
public BinaryTreeNode getRight() {
return right;
}
public void setRight(BinaryTreeNode right) {
this.right = right;
}
}
以下分别介绍介绍二叉树的四种遍历方法
1.前序遍历
public static void preOrder(BinaryTreeNode bt){
Stack<BinaryTreeNode> stack=new Stack<BinaryTreeNode>();
if(bt!=null){
stack.push(bt);
while(!stack.empty()){
BinaryTreeNode t=stack.pop();
System.out.print(t.getElement()+",");
if(t.getRight()!=null)
{
stack.push(t.getRight());
}
if(t.getLeft()!=null){
stack.push(t.getLeft());
}
}
}
}
2.中序遍历
public static void InOrder(BinaryTreeNode bt){
Stack<BinaryTreeNode> stack=new Stack<BinaryTreeNode>();
BinaryTreeNode cur=bt;
while(cur!=null||stack.size()>0){
while(cur!=null){
stack.push(cur);
cur=cur.getLeft();
}
if(stack.size()>0){
cur=stack.pop();
System.out.print(cur.getElement()+" ");
cur=cur.getRight();
}
}
}
3.后续遍历
public static void postOrder(BinaryTreeNode bt){
Stack<BinaryTreeNode> stack=new Stack<>();
BinaryTreeNode t=bt;
BinaryTreeNode prev=bt;
while(t!=null||stack.size()>0){
while(t!=null){
stack.push(t);
t=t.getLeft();
}
if(stack.size()>0){
BinaryTreeNode temp=stack.peek().getRight();
if(temp==null||temp==prev){
t=stack.pop();
System.out.print(t.getElement()+" ");
prev=t;
t=null;
}
else{
t=temp;
}
}
}
}
4.层次遍历
public static void levelOrder(BinaryTreeNode bt){
Queue<BinaryTreeNode> queue=new LinkedList<BinaryTreeNode>();
BinaryTreeNode t=bt;
if(t!=null)
queue.offer(t);
while(queue.size()>0){
BinaryTreeNode s=queue.poll();
System.out.print(s.getElement()+" ");
if(s.getLeft()!=null)
queue.offer(s.getLeft());
if(s.getRight()!=null)
queue.offer(s.getRight());
}
}