二叉树遍历
public class BiTree {
public static class TreeNode {
TreeNode lchild;
TreeNode rchild;
String value;
int mark=0;
}
public void preOrder(TreeNode root) {
if (root != null) {
visit(root);
preOrder(root.lchild);
preOrder(root.rchild);
}
}
public void preOrderNonRecursive(TreeNode root) {
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode p = root;
while (p != null || !stack.isEmpty()) {
if (p != null) {
visit(p);
stack.push(p);
p = p.lchild;
} else {
TreeNode x = stack.pop();
p = x.rchild;
}
}
}
public void middleOrder(TreeNode root) {
if (root != null) {
middleOrder(root.lchild);
visit(root);
middleOrder(root.rchild);
}
}
public void middleOrderNonRecursive(TreeNode root) {
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode p = root;
while (p != null || !stack.isEmpty()) {
if (p != null) {
stack.push(p);
p = p.lchild;
} else {
TreeNode x = stack.pop();
visit(x);
p = x.rchild;
}
}
}
public void afterOrder(TreeNode root) {
if (root != null) {
afterOrder(root.lchild);
afterOrder(root.rchild);
visit(root);
}
}
public void afterOrderNonRecursive(TreeNode root) {
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode p = root;
while (p != null || !stack.isEmpty()) {
if (p != null) {
stack.push(p);
p = p.lchild;
} else {
TreeNode x = stack.pop();
if (x.rchild == null || x.rchild.mark==1) {
if (x.mark == 0) {
x.mark = 1;
visit(x);
}
}else{
stack.push(x);
p=x.rchild;
}
}
}
}
public void levelOrder(TreeNode root) {
Deque<TreeNode> queue = new ArrayDeque<>();
if (root != null) {
queue.add(root);
}
while (queue.size() > 0) {
TreeNode t = queue.pop();
visit(t);
if (t.lchild != null) {
queue.add(t.lchild);
}
if (t.rchild != null) {
queue.add(t.rchild);
}
}
}
private void visit(TreeNode root) {
System.out.print(root.value);
}
public static void main(String[] args) {
TreeNode root = new TreeNode();
root.value = "A";
TreeNode b = new TreeNode();
b.value = "B";
TreeNode c = new TreeNode();
c.value = "C";
TreeNode d = new TreeNode();
d.value = "D";
TreeNode e = new TreeNode();
e.value = "E";
TreeNode h = new TreeNode();
h.value = "H";
root.lchild = b;
root.rchild = c;
c.lchild = d;
c.rchild = e;
b.lchild = h;
BiTree bi = new BiTree();
bi.preOrder(root);
System.out.println();
bi.preOrderNonRecursive(root);
System.out.println("\n============");
bi.middleOrder(root);
System.out.println();
bi.middleOrderNonRecursive(root);
System.out.println("\n============");
bi.afterOrder(root);
System.out.println();
bi.afterOrderNonRecursive(root);
System.out.println("\n============");
bi.levelOrder(root);
}
}