二叉树前、中、后遍历

public class Order{

    static class TreeNode {
        String val;
        TreeNode left;
        TreeNode right;

        TreeNode(String x) {
            val = x;
        }
    }
	//前序
    static void preOrder(TreeNode root) {
        Stack<TreeNode> stack = new Stack();
        TreeNode cur = root;
        while (cur != null || !stack.empty()) {
            if (cur != null) {
                System.out.println(cur.val);
                stack.push(cur);
                cur = cur.left;
            } else {
                TreeNode pop = stack.pop();
                cur = pop.right;
            }
        }
    }
	//中序
    static void inOrder(TreeNode root) {
        Stack<TreeNode> stack = new Stack();
        TreeNode cur = root;
        while (cur != null || !stack.empty()) {
            if (cur != null) {
                stack.push(cur);
                cur = cur.left;
            } else {
                TreeNode pop = stack.pop();
                System.out.println(pop.val);
                cur = pop.right;
            }
        }
    }
	//后序
    static void postOrder(TreeNode root) {
        Stack<TreeNode> stack = new Stack();
        stack.push(root);
        TreeNode cur, pre = null;
        while (!stack.empty()) {
            cur = stack.peek();
            if ((cur.left == null && cur.right == null) || 
            		(pre != null && (pre == cur.left || pre == cur.right))) {
                System.out.println(cur.val);
                pre = stack.pop();
            } else {
                if (cur.right != null) {
                    stack.push(cur.right);
                }
                if (cur.left != null) {
                    stack.push(cur.left);
                }
            }
        }
    }

    /**
     *           a
     * 		 /	    
     *     b          f
     *   /         /   
     *  c     d    g     h
     *       /
     *      e
     * 前序:abcdefgh
     * 后序:cedbghfa
     * 中序:cbedagfh
     */
    public static void main(String[] args) {
        TreeNode a = 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");

        a.left = b;
        b.left = c;
        b.right = d;
        d.left = e;
        a.right = f;
        f.left = g;
        f.right = h;

        inOrder(a);
    }
}

原文地址:https://www.cnblogs.com/paper-man/p/13284624.html