import java.util.Scanner;
class BinTree {
char data;
BinTree L,R;
BinTree(char x){
data=x;
}
static BinTree create(ReadChar r){
char x=r.getChar();
if(x=='#'){
return null;
}
BinTree t=new BinTree(x);
t.L=create(r);
t.R=create(r);
return t;
}
void pre(){
System.out.println(this.data+" ");
if(this.L!=null)
this.L.pre();
if(this.R!=null)
this.R.pre();
}
void in(){
if(this.L!=null)
this.L.in();
System.out.println(this.data+" ");
if(this.R!=null)
this.R.in();
}
void post(){
if(this.L!=null)
this.L.post();
if(this.R!=null)
this.R.post();
System.out.println(this.data+" ");
}
class Stack {
int top;
BinTree[] s=new BinTree[20];
boolean isEmpty(){
return top==0;
}
void push(BinTree x){
if(top==s.length){
BinTree[] news=new BinTree[s.length+20];
for(int i=0;i<s.length;i++){
news[i]=s[i];
s=news;
}
}
s[top]=x;
top++;
}
BinTree pop(){
top--;
return s[top];
}
}
void preN(){
BinTree t=this;
Stack st=new Stack();
while(t!=null||st.isEmpty()==false){
if(t!=null){
System.out.println(t.data+" ");
st.push(t);
t=t.L;
}
else{
t=st.pop();
t=t.R;
}
}
}
void inN(){
BinTree t=this;
Stack st=new Stack();
while(t!=null||st.isEmpty()==false){
if(t!=null){
st.push(t);
t=t.L;
}
else{
t=st.pop();
System.out.println(t.data+" ");
t=t.R;
}
}
}
}
class ReadChar {
String data;
int i=0;
ReadChar(String d){
data=d;
}
char getChar(){
char x=data.charAt(i);
i++;
return x;
}
}
class App {
public static void main(String[] args) {
System.out.println("请输入建树数据,#表示null:");
//AB#D##CE##F##
Scanner sc = new Scanner(System.in);
String str=sc.next();
ReadChar r=new ReadChar(str);
BinTree t=BinTree.create(r);
System.out.println("pre=");
t.pre();
System.out.println("preN=");
t.preN();
System.out.println("in=");
t.in();
System.out.println("inN=");
t.inN();
System.out.println("post=");
t.post();
}
}
javase二叉树作业备份
于 2022-09-19 22:38:27 首次发布