importjava.util.*;classNode{Nodeleft;NodeRight;chardata;//节点数据voidprint(){System.out.println(data+"");}publicNode(){this.left=null;this.Right=null;}publicNode(chardat...
import java.util.*;
class Node{
Node left;
Node Right;
char data;//节点数据
void print()
{
System.out.println(data+"");
}
public Node()
{
this.left=null;
this.Right=null;
}
public Node(char data){
this.left=null;
this.Right=null;
this.data=data;
}
}
class BTree {
static Node root=new Node();//为根节点分配空间
static char ch[];//输入的字符串
static void CreateTree(Node node)//先序建立二叉树
{
int i=0;
if(ch[i]=='#')
{
node=null;
i++;
}
else
{
node=new Node(ch[i]);i++;
CreateTree(node.left);
CreateTree(node.Right);
}
}
static public void preorder(Node node)//先序遍历二叉树
{
if(node!=null){
node.print();
preorder(node.left);
preorder(node.Right);
}
else{
System.out.println("Tree node is empty");
}
}
}
public class Tree{
public static void main(String args[])
{
Scanner reader=new Scanner(System.in);
char ch[]=new char[10];
ch[0]='a';
for(int i=0;ch[i]!='*';i++)//读取输入字符数组,以*结尾
ch[i]=reader.next().charAt(0);
BTree.CreateTree(BTree.root);
BTree.preorder(BTree.root);
}
}
展开