前序非递归遍历
import java.util.*;
class TreeNode{
char data;
TreeNode left;
TreeNode right;
public TreeNode(char data){
this.data=data;
this.right=null;
this.left=null;
}
}
class BiTree{
static int index=0;
public TreeNode CreateTree(String str){
if(index>str.length())
return null;
if(str.charAt(index)=='#')
{
index++;
return null;
}
else
{
TreeNode root= new TreeNode(str.charAt(index));
index++;
root.left=CreateTree(str);
root.right=CreateTree(str);
return root;
}
}
public void PreOrder(TreeNode root){
int top=-1;
TreeNode[] s=new TreeNode[105];
while(root!=null || top!=-1)
{
while(root!=null)
{
System.out.print(root.data);
s[++top] = root;
root = root.left;
}
if(top!=-1)
{
root=s[top--];
root=root.right;
}
}
}
public void setIndex(){index=0;}
}
public class Main{
public static void main(String args[]){
Scanner in=new Scanner(System.in);
while(in.hasNext())
{
String s=in.next();
BiTree tree=new BiTree();
TreeNode root=tree.CreateTree(s);
tree.PreOrder(root);
tree.setIndex();
System.out.println();
}
}
}