QueueNode:
package date1130;
public class QueueNode<T> {
T data;
public QueueNode<T> next;
}
Queue:
package date1130;
public class Queue<T> {
private QueueNode<T> first = null;
private QueueNode<T> last = null;
// 删除头部元素
public T remove() {
if (first == null) {
return null;
}
QueueNode<T> temp = first;
first = first.next;
return (T) temp.data;
}
// 尾部插入
protected void add(T value) {
QueueNode<T> node = new QueueNode<T>();
node.data = value;
node.next = null;
if (first == null) {
first = node;
last = first;
} else {
last.next = node;
last = node;
}
}
public boolean isEmpty() {
return first == null;
}
}
TreeNode:
public class TreeNode {
char data;
TreeNode leftNode;
TreeNode rightNode;
}
treeTesrt:
package date1130;
public class treeTesrt {
static int i = 0;
public static void main(String[] args) {
String str = "ABD00E00CF000";
// String str = "ABDEH00I00E0J00CF0K00G000";
char[] array = str.toCharArray();
TreeNode root = createTree(array);
System.err.println("前序遍历:");
preOrderTraverse(root);
System.err.println("\n中序遍历:");
inOrderTraverse(root);
System.err.println("\n后序遍历:");
postOrderTraverse(root);
System.err.println("\n层序遍历:");
levelTravel(root);
}
private static TreeNode createTree(char[] array) {
char c = array[i];
i++;
TreeNode node;
if ('0' == c) {
node = null;
} else {
node = new TreeNode();
node.data = c;
node.leftNode = createTree(array);
node.rightNode = createTree(array);
}
return node;
}
private static void preOrderTraverse(TreeNode node) {
if (null != node) {
System.err.print(node.data + " ");
preOrderTraverse(node.leftNode);
preOrderTraverse(node.rightNode);
}
}
private static void inOrderTraverse(TreeNode node) {
if (null != node) {
inOrderTraverse(node.leftNode);
System.err.print(node.data + " ");
inOrderTraverse(node.rightNode);
}
}
private static void postOrderTraverse(TreeNode node) {
if (null != node) {
postOrderTraverse(node.leftNode);
postOrderTraverse(node.rightNode);
System.err.print(node.data + " ");
}
}
/**
*
* @param root
* 树根节点
* 层序遍历二叉树,用队列实现,先将根节点入队列,只要队列不为空,然后出队列,并访问,接着讲访问节点的左右子树依次入队列
*/
public static void levelTravel(TreeNode root) {
if (root == null)
return;
Queue<TreeNode> queue = new Queue<TreeNode>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode temp = queue.remove();
System.err.print(temp.data + " ");
if (temp.leftNode != null)
queue.add(temp.leftNode);
if (temp.rightNode != null)
queue.add(temp.rightNode);
}
}
}