public class LevelOrder {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> treeList = new ArrayList<>();
if (root == null) return treeList;
List<TreeNode> NodeList = new ArrayList<>();
NodeList.add(root);
while (!NodeList.isEmpty()) {
List<TreeNode> tempList = new ArrayList<>();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < NodeList.size(); i++) {
list.add(NodeList.get(i).val);
if (NodeList.get(i).left != null) {
tempList.add(NodeList.get(i).left);
}
if (NodeList.get(i).right != null) {
tempList.add(NodeList.get(i).right);
}
}
treeList.add(list);
NodeList = tempList;
}
return treeList;
}
public 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;
}
}
}
|