1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Queue;
public class LeetCode102 { class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } } public List<List<Integer>> breadthfirst(TreeNode root){ List<List<Integer>> list = new ArrayList<>();
Queue<TreeNode> queue = new ArrayDeque<>(); if (root != null){ queue.add(root); } while (!queue.isEmpty()){ int n = queue.size(); List<Integer> level = new ArrayList<>(); for (int i = 0; i < n; i++){ TreeNode node = queue.poll(); level.add(node.val); if(node.left != null){ queue.add(node.left); } if (node.right != null){ queue.add(node.right); } } list.add(level); } return list; } }
|