目录
二叉树结点
package Tree;
public class TreeNode {
char data;
TreeNode left;
TreeNode right;
public void setLeft(TreeNode left) {
this.left = left;
}
public void setRight(TreeNode right) {
this.right = right;
}
}
二叉树的构造及遍历(层次遍历需要使用队列)
package Tree;
import java.io.IOException;
import java.util.Scanner;
public class TreeTool {
//构造树(先序法)
public static TreeNode CreateTree(TreeNode tree) {
//逐行读取单个字符方式
/*Scanner sc=new Scanner(System.in);
char c=sc.next().charAt(0);*/
//一行逐个读取单个字符方式(字符必须相邻)
char c = 0;
try {
c = (char)System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
if (c=='#') { //递归结束标志:'#'字符
return null;
}
else{
//tree=new TreeNode(); //引用方式,此句会让tree指向新的内存空间,原内存空间
//并未改变,尽管原内存指向为null,这里再new同样会指向
//新内存空间。
tree.data=c;
tree.setLeft(CreateTree(new TreeNode()));
tree.setRight(CreateTree(new TreeNode()));
return tree;
}
}
//先序遍历树
public static void pre(TreeNode T) {
if (T!=null) { //当T==null是递归结束标志
System.out.println(T.data);
pre(T.left);
pre(T.right);
}
}
//中序遍历树
public static void now(TreeNode T) {
if (T!=null) { //当T==null是递归结束标志
now(T.left);
System.out.println(T.data);
now(T.right);
}
}
//后序遍历树
public static void after(TreeNode T) {
if (T!=null) { //当T==null是递归结束标志
after(T.left);
after(T.right);
System.out.println(T.data);
}
}
//层次遍历
public static void level(TreeNode T) {
OrderQueue queue=new OrderQueue();
if (T!=null) {
queue.entry(T); //根结点入队
while (queue.getStart()!=null) { //当队列未空时
TreeNode treeNode=(TreeNode) queue.exit();
System.out.println(treeNode.data);
if (treeNode.left!=null) {
queue.entry(treeNode.left);
}
if (treeNode.right!=null) {
queue.entry(treeNode.right);
}
}
}
}
}