通过两个栈交替使用遍历即可。

需要注意的时候用栈的时候需要反向思考入栈和出栈的顺序。

import java.util.*;

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    
    public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer> > result = new ArrayList<ArrayList<Integer> >();
        if (pRoot == null) {
            return result;
        }
        Stack<TreeNode> stack1 = new Stack();
        Stack<TreeNode> stack2 = new Stack();
        stack1.push(pRoot);
        boolean lr = true;
        while(!stack1.isEmpty() || !stack2.isEmpty()) {
            ArrayList<Integer> list = new ArrayList<>();
            if (lr) {
                while(!stack1.isEmpty()) {
                    TreeNode node = stack1.pop();
                    list.add(node.val);
                    if(node.left != null) {
                        stack2.push(node.left);
                    }
                    if(node.right != null) {
                        stack2.push(node.right);
                    }
                }
            } else {
                while(!stack2.isEmpty()) {
                    TreeNode node = stack2.pop();
                    list.add(node.val);
                    if(node.right != null) {
                        stack1.push(node.right);
                    }
                    if(node.left != null) {
                        stack1.push(node.left);
                    }
                }
            }
            lr = !lr;
            result.add(list);
        }
        return result;
    }
}