public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); if (root == null) { return result; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); boolean flagOdd = true; while (!queue.isEmpty()) { int qsize = queue.size(); List<Integer> subResult = new ArrayList<Integer>(); for (int i = 0; i < qsize; i++) { TreeNode node = queue.poll(); subResult.add(node.val); if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } } if (flagOdd) { result.add(subResult); } else { Collections.reverse(subResult); result.add(subResult); } flagOdd = !flagOdd; } return result; }
public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> ret = new ArrayList(); if (root == null) return ret; helper(ret, root, 1); Collections.reverse(ret); return ret; }
/** * @param root: The root of binary tree. * @return: buttom-up level order a list of lists of integer */ public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) { // write your code here Queue<TreeNode> q = new LinkedList<TreeNode>(); ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); if (root == null) return res; q.add(root); while (!q.isEmpty()) { ArrayList<Integer> cur = new ArrayList<Integer>(); int size = q.size(); for (int i = 0; i < size; i++) { TreeNode temp = q.poll(); cur.add(temp.val); if (temp.left != null) q.add(temp.left); if (temp.right != null) q.add(temp.right); } res.add(cur); } Collections.reverse(res); return res; }
// @RubyLevelMethod(name="reverse!") public RubyArray reverseBang() { Collections.reverse(array_); return this; }
// @RubyLevelMethod(name="reverse") public RubyArray reverse() { RubyArray array = this.copy(); Collections.reverse(array.array_); return array; }