public static void main(String[] args) {
BinaryTree<Character> binaryTree = new BinaryTree<Character>();
// 输入ABDH##I##E##CF#J##G##(#用null代替)
LinkedList<Character> tree = new LinkedList<Character>();
tree.add('A');
tree.add('B');
tree.add('D');
tree.add('H');
tree.add(null);
tree.add(null);
tree.add('I');
tree.add(null);
tree.add(null);
tree.add('E');
tree.add(null);
tree.add(null);
tree.add('C');
tree.add('F');
tree.add(null);
tree.add('J');
tree.add(null);
tree.add(null);
tree.add('G');
tree.add(null);
tree.add(null);
TreeNode<Character> root = binaryTree.creatBinaryPre(tree);
// 先序遍历(递归)
binaryTree.PrintBinaryTreePreRecur(root);
System.out.println();
// 中序遍历(递归)
binaryTree.PrintBinaryTreeMidRecur(root);
System.out.println();
// 后序遍历(递归)
binaryTree.PrintBinaryTreeBacRecur(root);
System.out.println();
// 先序遍历(非递归)
binaryTree.PrintBinaryTreePreUnRecur(root);
System.out.println();
// 中序遍历(非递归)
binaryTree.PrintBinaryTreeMidUnrecur(root);
System.out.println();
// 后序遍历(非递归)
binaryTree.PrintBinaryTreeBacUnrecur(root);
System.out.println();
// 层次遍历(非递归)
}
// 先序遍历,返回根节点
public TreeNode createBinaryPre(LinkedList<T> treeData) {
TreeNode root = null;
T data = treeData.removeFirst();
if (data != null) {
root = new TreeNode<T>(data, null, null);
root.left = creatBinaryPre(treeData);
root.right = creatBinaryPre(treeData);
}
return root;
}
public void PrintBinaryTreePreRecur(TreeNode<T> root) {
if (root != null) {
System.out.println(root.data);
PrintBinaryTreePreRecur(root.left);
PrintBinaryTreePreRecur(root.right);
}
}
@SuppressWarnings("unchecked")
public void PrintBinaryTreePreUnRecur(TreeNode<T> root) {
TreeNode<T> p = root;
LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
while (p != null && !stack.isEmpty()) {
if (p != null) {
stack.push(p);
System.out.println(p.data);
p = p.left;
} else {
p = stack.pop();
p = p.right;
}
}
}
public void PrintBinaryTreeMidRecur(TreeNode<T> root) {
if (root != null) {
PrintBinaryTreeMidRecur(root.left);
System.out.println(root.data);
PrintBinaryTreeMidRecur(root.right);
}
}
public void PrintBinaryTreeMidUnrecur(TreeNode<T> root) {
TreeNode<T> p = root;// p为当前节点
LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
// 栈不为空时,或者p不为空时循环
while (p != null || !stack.isEmpty()) {
// 当前节点不为空。压入栈中。并将当前节点赋值为左儿子
if (p != null) {
stack.push(p);
p = p.left;
}
// 当前节点为空:
// 1、当p指向的左儿子时,此时栈顶元素必然是它的父节点
// 2、当p指向的右儿子时,此时栈顶元素必然是它的爷爷节点
// 取出并访问栈顶元素,赋值为right
else {
p = stack.pop();
System.out.print(p.data);
p = p.right;
}
}
}