首页 > 其他 > 详细

之字形打印二叉树

时间:2017-09-17 17:15:22      阅读:358      评论:0      收藏:0      [点我收藏+]
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;

	}

之字形打印二叉树

原文:http://www.cnblogs.com/blythe/p/7536026.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!