二叉树非递归遍历

package test;


public class Tree {
private class Node{
private Node left;
private Node right;
private int data;
public Node(int data){
this.data=data;
}
}
private int len;
private Node t[];
private Node stack[];
private int stack0[];
private int top = -1;

public Tree(int len){
this.len = len;
}

//前序访问
private void preVisit(Node t){
if(t != null){
Node p = t;
do{
while(p!=null ){
visit(p);
stack[++top]=p;
p = p.left;
}
p = stack[top--];
p = p.right;
}while(top!=-1 || p!=null);
}
}

//中序访问
private void midVisit(Node t){
if(t != null){
Node p = t;
do{
while(p!=null){
stack[++top] = p;
p = p.left;
}
p = stack[top--];
visit(p);
p = p.right;
}while(top!=-1 || p!=null);
}
}

//后序访问
private void afterVisit(Node t){
if(t!=null){
Node p = t;
do{
while(p!=null){
stack[++top] = p;
stack0[top] = 0;
p = p.left;
}
p = stack[top];
int flag = stack0[top--];
if(flag == 0){
stack[++top] = p;
stack0[top] = 1;
p = p.right;
}else{
visit(p);
p = null;
}
}while(p!=null || top!=-1);
}
}

private void visit(Node p){
char info[] = {'A','B','C','D','E','F','G','H'};
System.out.print(info[p.data]);
}

private void inital(){
stack = new Node [len];
stack0  = new int [len];

t = new Node[len];
for(int i = 0; i < len; i++){
t[i] = new Node(i);
}
t[0].left = t[1];
t[0].right = t[2];
t[1].left = t[3];
t[1].right = t[4];
t[2].left = t[5];
t[2].right = null;
t[3].left = null;
t[3].right = null;
t[4].left = t[6];
t[4].right = null;
t[5].left = null;
t[5].right = t[7];
t[6].left = null;
t[6].right = null;
t[7].left = null;
t[7].right = null;
}

public static void main(String args[]){
Tree t = new Tree(8);
t.inital();
t.preVisit(t.t[0]);
t.midVisit(t.t[0]);
t.afterVisit(t.t[0]);
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值