Title:
Given a binary tree node to return its value in a 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]
]
/**
- Results returned by the observation of a large collection can be nested up to a small set, it requires two sets;
- Queue sets a queue, to hold the elements of each layer, and set a variable COUNT int type, this layer has recorded several elements;
- Each traversed layer, this layer is put queue element to poll off and added to the collection; poll difference and pop, pop null Throws
- If the left node and a right node through the previous values stored in the queue is determined to be blank the next layer is added to the queue elements (since only the binary tree left node and a right node);
- Cycle is repeated until the queue is empty.
* /
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> resultList = new ArrayList<>();
if(root == null)
return resultList;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
//将每层的节点放入Queue
while(!queue.isEmpty()){
List<Integer> levelList = new ArrayList<>();
int count = queue.size();
for(int i=0;i<count;i++){
TreeNode node = queue.poll();
levelList.add(node.val);
if(node.left!=null){
queue.add(node.left);
}
if(node.right!=null){
queue.add(node.right);
}
}
resultList.add(levelList);
}
return resultList;
}