0%

Leetcode102-binaryTreeLevelOrderTraversal

Description

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

Example

1
2
3
4
5
6
7
8
9
10
11
12
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<List<Integer>> res = new ArrayList<>();

public void traversal(TreeNode node, int level){
if (res.size() <= level) res.add(new ArrayList<>());
res.get(level).add(node.val);
if (node.left != null) traversal(node.left, level + 1);
if (node.right != null) traversal(node.right, level + 1);
}
public List<List<Integer>> levelOrder(TreeNode root) {
if (root == null) return res;
traversal(root, 0);
return res;
}
}