标签:
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; } }
学习之处:
Binary Tree Zigzag Level Order Traversal
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4337942.html