Binary Tree Zigzag Level Order Traversal
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).
思路:
队列层次访问
我的代码:
public class Solution { public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> rst = new ArrayList<List<Integer>>(); if(root == null) return rst; Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); int count = 1; while(!queue.isEmpty()) { int size = queue.size(); List<Integer> list = new ArrayList<Integer>(); for(int i = 0; i < size; i++) { TreeNode node = queue.poll(); if(node.left != null) queue.offer(node.left); if(node.right != null) queue.offer(node.right); list.add(node.val); } if(count%2 == 1) { rst.add(list); } else { Collections.reverse(list); rst.add(list); } count++; } return rst; } }
他人代码:
public class Solution { public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if (root == null) { return result; } Stack<TreeNode> currLevel = new Stack<TreeNode>(); Stack<TreeNode> nextLevel = new Stack<TreeNode>(); Stack<TreeNode> tmp; currLevel.push(root); boolean normalOrder = true; while (!currLevel.isEmpty()) { ArrayList<Integer> currLevelResult = new ArrayList<Integer>(); while (!currLevel.isEmpty()) { TreeNode node = currLevel.pop(); currLevelResult.add(node.val); if (normalOrder) { if (node.left != null) { nextLevel.push(node.left); } if (node.right != null) { nextLevel.push(node.right); } } else { if (node.right != null) { nextLevel.push(node.right); } if (node.left != null) { nextLevel.push(node.left); } } } result.add(currLevelResult); tmp = currLevel; currLevel = nextLevel; nextLevel = tmp; normalOrder = !normalOrder; } return result; } }
学习之处:
- 虽然使用队列也能实现该问题,但是仔细想想,如果这一层的最右节点是这层的最后一个元素,那么它的right节点是下一层的最后一个访问的,如果这一层的最左节点是该层访问的最后一个元素,那么该元素的Left将是下一层访问的节点,故由此分析,使用Stack比queue要更加合理,而且如此一来,也能节约掉Queue方法下面的链表翻转的时间。
posted on 2015-03-14 17:54 zhouzhou0615 阅读(155) 评论(0) 编辑 收藏 举报