class Solution {
List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> levelOrder(TreeNode root) {
if (root == null) {
return result;
}
traverse(root, 0);
return result;
}
private void traverse(TreeNode node, int level) {
if (result.size() == level) {
result.add(new ArrayList<>());
}
result.get(level).add(node.val);
if (node.left != null) {
traverse(node.left, level + 1);
}
if (node.right != null) {
traverse(node.right, level + 1);
}
}
}
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
List<Integer> level = new ArrayList<>();
Stack<TreeNode> nextLevel = new Stack<>();
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
level.add(node.val);
if (node.right != null) {
nextLevel.push(node.right);
}
if (node.left != null) {
nextLevel.push(node.left);
}
}
result.add(level);
stack = nextLevel;
}
return result;
}
}
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
List<Integer> level = new ArrayList<>();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
level.add(node.val);
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
result.add(level);
}
return result;
}
}