前中后序的非递归实现
class TreeNode{
char value;
TreeNode left;
TreeNode right;
public TreeNode(char value){
this.value=value;
}
}
public class BinaryTree {
public TreeNode buildTree() {
TreeNode root = new TreeNode('A');
TreeNode B = new TreeNode('B');
TreeNode C = new TreeNode('C');
TreeNode D = new TreeNode('D');
TreeNode E = new TreeNode('E');
TreeNode F = new TreeNode('F');
TreeNode G = new TreeNode('G');
TreeNode H = new TreeNode('H');
root.left = B;
root.right = C;
B.left = D;
B.right = E;
E.right = H;
C.left = F;
C.right = G;
return root;
}
//1. 二叉树的前序遍历,非递归迭代实现
//链表形式
List<Character> preOrderTraversalNOR(TreeNode root) {
List<Character> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (cur != null || !stack.empty()) {
while (cur != null) {
stack.push(cur);
System.out.print(cur.value + " ");
list.add(cur.value);
cur = cur.left;
}
cur = stack.pop();
cur = cur.right;
}
return list;
}
//2. 二叉树的中序遍历,非递归迭代实现
List<Character> inOrderTraversalNOR(TreeNode root) {
List<Character> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (cur != null || !stack.empty()) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
list.add(cur.value);
System.out.print(cur.value + " ");
cur = cur.right;
}
return list;
}
//3. 二叉树的后序遍历,非递归迭代实现
public List<Character> postorderTraversal(TreeNode root){
List<Character> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
TreeNode prev = null;
while (cur != null || !stack.empty()){
while (cur != null){
stack.push(cur);
cur = cur.left;
}
cur=stack.peek();
if(cur.right==null || cur.right==prev){
stack.pop();
System.out.print(cur.value+" ");
list.add(cur.value);
prev=cur;//防止结点被重复打印
cur=null;
}else {
cur = cur.right;
}
}
return list;
}
public static void main(String[] args) {
//1. 二叉树的前序遍历,非递归迭代实现
BinaryTree binaryTree=new BinaryTree();
TreeNode root=binaryTree.buildTree();
binaryTree.preOrderTraversalNOR(root);
System.out.println();
//2. 二叉树的中序遍历,非递归迭代实现
binaryTree.inOrderTraversalNOR(root);
//3. 二叉树的后序遍历,非递归迭代实现
System.out.println();
binaryTree.postorderTraversal(root);
}
}