|
| 1 | +import java.util.ArrayList; |
| 2 | +import java.util.LinkedList; |
| 3 | +import java.util.List; |
| 4 | + |
| 5 | +/** |
| 6 | + * Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). |
| 7 | + * <p> |
| 8 | + * For example: |
| 9 | + * Given binary tree [3,9,20,null,null,15,7], |
| 10 | + * 3 |
| 11 | + * / \ |
| 12 | + * 9 20 |
| 13 | + * /\ |
| 14 | + * 15 7 |
| 15 | + * return its level order traversal as: |
| 16 | + * [ |
| 17 | + * [3], |
| 18 | + * [9,20], |
| 19 | + * [15,7] |
| 20 | + * ] |
| 21 | + * <p> |
| 22 | + * Accepted. |
| 23 | + */ |
| 24 | + |
| 25 | +public class BinaryTreeLevelOrderTraversal { |
| 26 | + |
| 27 | + public List<List<Integer>> levelOrder(TreeNode root) { |
| 28 | + List<List<Integer>> lists = new ArrayList<>(); |
| 29 | + helper(lists, root, 0); |
| 30 | + return lists; |
| 31 | + } |
| 32 | + |
| 33 | + private void helper(List<List<Integer>> res, TreeNode node, int height) { |
| 34 | + if (node == null) { |
| 35 | + return; |
| 36 | + } |
| 37 | + if (height >= res.size()) { |
| 38 | + res.add(new LinkedList<>()); |
| 39 | + } |
| 40 | + res.get(height).add(node.val); |
| 41 | + helper(res, node.left, height + 1); |
| 42 | + helper(res, node.right, height + 1); |
| 43 | + } |
| 44 | + |
| 45 | + public static class TreeNode { |
| 46 | + |
| 47 | + int val; |
| 48 | + TreeNode left; |
| 49 | + TreeNode right; |
| 50 | + |
| 51 | + TreeNode(int x) { |
| 52 | + val = x; |
| 53 | + } |
| 54 | + |
| 55 | + @Override |
| 56 | + public boolean equals(Object obj) { |
| 57 | + if (obj instanceof TreeNode) { |
| 58 | + TreeNode node = (TreeNode) obj; |
| 59 | + if (this.val != node.val) { |
| 60 | + return false; |
| 61 | + } |
| 62 | + if (this.left == null) { |
| 63 | + if (this.right == null) { |
| 64 | + return node.left == null && node.right == null; |
| 65 | + } |
| 66 | + return this.right.equals(node.right); |
| 67 | + } |
| 68 | + if (this.right == null) { |
| 69 | + return node.right == null; |
| 70 | + } |
| 71 | + return this.left.equals(node.left) && this.right.equals(node.right); |
| 72 | + } |
| 73 | + return false; |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | +} |
0 commit comments