https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
解题思路:
这道题用的是二叉树的层次遍历,难度不大,但是有点绕。开始想到用deque来做,最后发现其实只要一个stack就可以了。
具体是,我们令第一层为1。这样遍历奇数层的时候,奇数层是从左到有输出,但由于它的下一层(偶数层)是要从右到左输出的,我们就先将左子树进栈,再将右子树进栈。
同理,遍历偶数层的时候,偶数层是从右到左遍历的,下一层要从左到右输出,我们就先将右子树进栈,再将左子树进栈。
其他过程和层次遍历没什么不同。
要注意的是:
1. 这里需要用到两个stack,用来维护当前层次的stack,和下一层次的stack。因为stack不是queue,push进元素的时候,就无法按照原来元素的顺序取出了。
2. 这里要注意因为每层的遍历顺序也不同,下一层的输出顺序也不同,所以只要stack就可以了,先进后出,并不需要deque。
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<List<Integer>>(); if(root == null) { return result; } Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(root); int level = 1; while(stack.size() > 0) { int size = stack.size(); Stack<TreeNode> nextLevelStack = new Stack<TreeNode>(); List<Integer> thisLevel = new ArrayList<Integer>(); while(size > 0) { TreeNode current = stack.pop(); thisLevel.add(current.val); if(level % 2 == 1) { if(current.left != null) { nextLevelStack.push(current.left); } if(current.right != null) { nextLevelStack.push(current.right); } } if(level % 2 == 0) { if(current.right != null) { nextLevelStack.push(current.right); } if(current.left != null) { nextLevelStack.push(current.left); } } size--; } result.add(thisLevel); level++; stack = nextLevelStack; } return result; } }
update 2015/05/18:
二刷,一个讨巧的解法,比上面容易理解多了。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<List<Integer>>(); if(root == null) { return result; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); int level = 0; while(queue.size() > 0) { int levelSize = queue.size(); List<Integer> levelList = new ArrayList<Integer>(); while(levelSize > 0) { TreeNode node = queue.poll(); if(level % 2 == 0) { levelList.add(node.val); } else { levelList.add(0, node.val); } levelSize--; if(node.left != null) { queue.offer(node.left); } if(node.right != null) { queue.offer(node.right); } } result.add(levelList); level++; } return result; } }