先序遍历(DLR)Data-Lchild-Rchild
// 先序遍历(DLR)Data-Lchild-Rchild
public void PreOrder(BiTreeNode tree){
if (tree != null){
System.out.println(tree);
PreOrder(tree.lchild);
PreOrder(tree.rchild);
}
}
中序遍历(LDR)Lchild-Data-Rchild
// 中序遍历(LDR)Lchild-Data-Rchild
public void InOrder(BiTreeNode tree){
if (tree != null){
InOrder(tree.lchild);
System.out.println(tree);
InOrder(tree.rchild);
}
}
中序非递归遍历
// 中序遍历的非递归算法
public void InOrder(BiTreeNode tree) {
LinkedList<BiTreeNode> stack = new LinkedList<>(); // 辅助栈
BiTreeNode pointer = tree; // 中序遍历的顺序指针
while (!stack.isEmpty() || pointer != null) {
if (pointer != null) { // 顺序指针非空说明仍有左孩子
stack.push(pointer);
pointer = pointer.lchild;
} else { // 顺序指针已指向最左叶结点,出栈结点并访问,然后指向这个结点的右孩子
BiTreeNode pop = stack.pop();
System.out.println(pop);
pointer = pop.rchild;
}
}
}
后序遍历(LRD)Lchild-Rchild-Data
// 后序遍历(LRD)Lchild-Rchild-Data
public void PostOrder(BiTreeNode tree){
if (tree != null){
PostOrder(tree.lchild);
PostOrder(tree.rchild);
System.out.println(tree);
}
}
后序非递归遍历
LinkedList<BiTreeNode> stack = new LinkedList<>(); // 辅助栈,存放二叉树遍历的顺序
BiTreeNode pointer; // 二叉树遍历的工作指针
BiTreeNode pre; // 前驱结点,遍历右子树回溯时保存刚刚访问的右孩子
// 后序遍历(LRD)Lchild-Rchild-Data
public void PostOrder(BiTreeNode tree){
LinkedList<BiTreeNode> stack = new LinkedList<>();
BiTreeNode pointer = tree;
BiTreeNode pre = null;
while (pointer != null || !stack.isEmpty()) {
if (pointer != null) {
stack.push(pointer);
pointer = pointer.lchild;
}
else if (!stack.isEmpty()) {
pointer = stack.getFirst(); // 获取栈顶但不出栈
if (pointer.rchild == null || pointer.rchild == pre) { // 如果p指针的右孩子为null或者p指针的右孩子刚访问过
System.out.println(pointer);
stack.pop();
pre = pointer;
pointer = null; // 如果p指针不置零,下次循环会找到p指针最左孩子的位置
} else {
pointer = pointer.rchild;
}
}
}
}