package org.example.interview.practice; import com.sun.jmx.remote.internal.ArrayQueue; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Objects; import java.util.Queue; /** * @author xianzhe.ma * @date 2021/8/21 */ public class NC_15_levelOrder { public static ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) { // write code here if (Objects.isNull(root)) { return new ArrayList<>(); } ArrayList<ArrayList<Integer>> retList = new ArrayList<>(); Queue<TreeNode> queue = new ArrayDeque<>(); queue.add(root); while (!queue.isEmpty()) { ArrayList<TreeNode> levelList = new ArrayList<>(); ArrayList<Integer> tempList = new ArrayList<>(); while (!queue.isEmpty()) { TreeNode node = queue.poll(); tempList.add(node.val); levelList.add(node); } for (TreeNode node : levelList) { if (Objects.nonNull(node.left)) { queue.add(node.left); } if (Objects.nonNull(node.right)) { queue.add(node.right); } } levelList = null; retList.add(tempList); } return retList; } public static class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } public static void main(String[] args) { TreeNode node0 = new TreeNode(1); // TreeNode node1 = new TreeNode(1); // TreeNode node2 = new TreeNode(2); // node0.right = node1; // node0.left = node2; // int result = sumNumbers(node0); // System.out.println(result); levelOrder(node0); } }