102. The binary tree hierarchy traversal
Given a binary tree, the node returns its value hierarchical traversal. (Ie, layer by layer, from left to right to access all nodes).
For example:
Given a binary tree: [3,9,20, null, null, 15,7],
3
/
920
/
157
to return to its level through the results:
[
[3],
[9,20],
[15,7]
]
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if(root == null)
return new ArrayList<>();
List<List<Integer>> res = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while(!queue.isEmpty()){
int count = queue.size();
List<Integer> list = new ArrayList<Integer>();
while(count > 0){
TreeNode node = queue.poll();
list.add(node.val);
if(node.left != null)
queue.add(node.left);
if(node.right != null)
queue.add(node.right);
count--;
}
res.add(list);
}
return res;
}
}