之字形打印二叉树

public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
		List<List<Integer>> ans = new ArrayList<>();
		if (root == null)
			return ans;
		// 使用两个栈维护顺序
		Stack<TreeNode> stack = new Stack<>();
		Stack<TreeNode> nextStack = new Stack<>();
		stack.add(root);
		int flag = 0;
		List<Integer> lay = new ArrayList<>();
		while (!stack.isEmpty()) {
			TreeNode node = stack.pop();
			lay.add(node.val);
			// 如果当前是从左到右遍历,按左子树右子树的顺序添加
			if (flag == 0) {
				if (node.left != null)
					nextStack.add(node.left);
				if (node.right != null)
					nextStack.add(node.right);
			} else// 如果当前是从右到左遍历,按右子树左子树的顺序添加
			{
				if (node.right != null)
					nextStack.add(node.right);
				if (node.left != null)
					nextStack.add(node.left);
			}
			if (stack.isEmpty()) {
				// 交换两个栈
				Stack<TreeNode> tmp = stack;
				stack = nextStack;
				nextStack = tmp;
				// 标记下一层处理的方向
				flag = 1 - flag;
				ans.add(new ArrayList<>(lay));
				lay.clear();
			}
		}
		return ans;

	}
原文地址:https://www.cnblogs.com/blythe/p/7536026.html