这是小弟写的二叉树的遍历,请各位指正,并且有一点:两个中序遍历的值怎么不一样啊?我没有想明白希望各位给个指点!结果为:
递归先根序
5 7 8 6 2 4 3 1 0 
非递归先根序
5 7 8 6 2 4 3 1 0 
递归中根序
7 8 6 5 2 4 3 1 0 
非递归中根序
8 7 6 5 4 3 2 1 0 
层次遍历
5 7 2 8 6 4 1 3 0public class BTree
{
public int value;
public BTree lchild;
public BTree rchild;

public static void main(String[] args)
{
int[] array = {2,4,7,3,6,8,1,0};
BTree root = new BTree();
root.value = 5;

for(int i=0; i<array.length; i++)
{
root.createBTree(array[i]);
}
System.out.println("递归先根序");
root.dgFirst();
System.out.println();

System.out.println("非递归先根序");
root.nonDgFirst(root);
System.out.println();

System.out.println("递归中根序");
root.dgMid();
System.out.println();

System.out.println("非递归中根序");
root.nonDgMid(root);
System.out.println();

System.out.println("层次遍历");
root.levelOrder(root);
System.out.println();
} public void createBTree(int value)
{
if(this.value<value)
{
if(this.lchild==null)
{
this.lchild = new BTree();
this.lchild.value = value;
}else
{
this.lchild.createBTree(value);
}
}
if(this.value>=value)
{
if(this.rchild==null)
{
this.rchild = new BTree();
this.rchild.value = value;
}else
{
this.rchild.createBTree(value);
}

}
}

public void dgFirst()
{
System.out.print(this.value+" ");
if(this.lchild!=null)
this.lchild.dgFirst();
if(this.rchild!=null)
this.rchild.dgFirst();
}

public void dgMid()
{
if(this.lchild!=null)
this.lchild.dgFirst();
System.out.print(this.value+" ");
if(this.rchild!=null)
this.rchild.dgFirst();
}

public void nonDgFirst(BTree root)
{
Stack<BTree> st = new Stack<BTree>();
BTree p;

if(root!=null)
{
p = st.push(root);

while(!st.isEmpty())
{
p = st.pop();
System.out.print(p.value+" ");

if(p.rchild!=null)
{
st.push(p.rchild);
}
if(p.lchild!=null)
{
st.push(p.lchild);
}
}
}
}

public void nonDgMid(BTree root)
{
Stack<BTree> stack = new Stack<BTree>();
BTree p = root;

if(root!=null)
{
while(!stack.isEmpty() || p!=null)
{
while(p!=null)
{
stack.push(p);
p = p.lchild;
}
if(!stack.isEmpty())
{
p = stack.pop();
System.out.print(p.value+" ");
p = p.rchild;
}
}
}
} public void levelOrder(BTree root)
{
Queue<BTree> queue = new LinkedList<BTree>();
queue.offer(root);

while(!queue.isEmpty())
{
BTree p = queue.poll();
System.out.print(p.value+" ");
if(p.lchild!=null)
{
queue.offer(p.lchild);
}
if(p.rchild!=null)
{
queue.offer(p.rchild);
}
}
}
}