poll if templeft null queueaddtempleft if tempright null queueaddtempright

Poll if templeft null queueaddtempleft if tempright

This preview shows page 1 - 3 out of 3 pages.

TreeNode temp = queue.poll(); if (temp.left != null) queue.add(temp.left); if (temp.right != null) queue.add(temp.right); currentLevel.add(temp.val); } currentRow.add(0, currentLevel); }
Image of page 1
return currentRow; } } public class MainClass { public static TreeNode stringToTreeNode(String input) { input = input.trim(); input = input.substring(1, input.length() - 1); if (input.length() == 0) { return null; } String[] parts = input.split(","); String item = parts[0]; TreeNode root = new TreeNode(Integer.parseInt(item)); Queue<TreeNode> nodeQueue = new LinkedList<>(); nodeQueue.add(root); int index = 1; while (!nodeQueue.isEmpty()) { TreeNode node = nodeQueue.remove(); if (index == parts.length) { break; } item = parts[index++]; item = item.trim(); if (!item.equals("null")) { int leftNumber = Integer.parseInt(item); node.left = new TreeNode(leftNumber); nodeQueue.add(node.left); } if (index == parts.length) { break; } item = parts[index++]; item = item.trim(); if (!item.equals("null")) { int rightNumber = Integer.parseInt(item); node.right = new TreeNode(rightNumber); nodeQueue.add(node.right); } } return root; } public static String integerArrayListToString(List<Integer> nums, int length) { if (length == 0) { return "[]"; } String result = ""; for (int index = 0; index < length; index++) { Integer number = nums.get(index); result += Integer.toString(number) + ", "; } return "[" + result.substring(0, result.length() - 2) + "]"; } public static String integerArrayListToString(List<Integer> nums) {
Image of page 2
return integerArrayListToString(nums, nums.size()); } public static String int2dListToString(List<List<Integer>> nums) { StringBuilder sb = new StringBuilder("["); for (List<Integer> list : nums) { sb.append(integerArrayListToString(list)); sb.append(","); } sb.setCharAt(sb.length() - 1, ']'); return sb.toString(); } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line; while ((line = in.readLine()) != null) { TreeNode root = stringToTreeNode(line); List<List<Integer>> ret = new Solution().levelOrderBottom(root); String out = int2dListToString(ret); System.out.print(out); } } }
Image of page 3

You've reached the end of your free preview.

Want to read all 3 pages?

  • Fall '19

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

Stuck? We have tutors online 24/7 who can help you get unstuck.
A+ icon
Ask Expert Tutors You can ask You can ask You can ask (will expire )
Answers in as fast as 15 minutes