public class TestBinaryTree implements ITestBinaryTree {
static class TreeNode {
char val;
TreeNode left;
TreeNode right;
public TreeNode(char val) {
this.val = val;
this.left = null;
this.right = null;
}
}
//非递归的二叉树前序遍历
@Override
public void binaryTreePrevOrderNonR(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
TreeNode top = null;
while (cur != null || !stack.empty()) {
while (cur != null) {
System.out.print(cur.val + " ");
stack.push(cur);
cur = cur.left;
}
top = stack.pop();
cur = top.right;
}
}
//非递归的中序遍历
@Override
public void binaryTreeInOrderNonR(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
TreeNode top = null;
while (cur != null || !stack.empty()) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
top = stack.pop();
System.out.print(top.val + " ");
cur = top.right;
}
}
//非递归的后序遍历
@Override
public void binaryTreePostOrderNonR(TreeNode root) {
TreeNode cur = root;
TreeNode pre = root;
Stack<TreeNode> stack = new Stack<>();
while (cur != null || !stack.isEmpty()) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.peek();
if (cur.right == null || cur.right == pre
) {
System.out.print(cur.val + " ");
stack.pop();
pre = cur;
cur = null;
} else {
cur = cur.right;
}
}
}
}
11-13