二叉树的遍历方法:先根遍历、中根遍历、后根遍历,见:《关于二叉树的前序、中序、后序三种遍历》

有二叉树如下:


    public static class TreeNode{
        TreeNode left;
        TreeNode right;
        String val;
        public TreeNode(String value){
            this.val  = value;
        }
    }

    public static void print(TreeNode root){
       //TODO 待实现
    }

    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");
        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        E.left = F;
        print(A);
	}

递归遍历:

    public static void print(TreeNode root){
        if(root == null){
            return;
        }
        System.out.print(root.val);
        print2(root.right);
        print2(root.left);
    }

不同的遍历需要调整print方法后三行的的顺序。

循环实现


    public static class Action{
        int type; // 0 visit, 1 print
        TreeNode node;
        Action(int type, TreeNode node){
            this.type = type;
            this.node = node;
        }
    }


    public static void print(TreeNode root){
        Stack<Action> path = new Stack<>();
        path.push(new Action(0, root));
        while(!path.empty()){
            Action action = path.pop();
            if(action == null || action.node == null){
                continue;
            }
            if(action.type == 1){
                System.out.print(action.node.val);
            } else {
                path.push(new Action(0, action.node.left));
                path.push(new Action(0, action.node.right));
                path.push(new Action(1, action.node));
            }
        }
    }

不同的遍历需要调整print方法else中三行的的顺序。