Binary Tree Level Order Traversal
题目
Given a binary tree, return thelevel ordertraversal of its nodes' values. (ie, from left to right, level by level).
For example:
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]
]
分析
- using BFS(Breadth-first search) to solve this problem
- why we need bother to assign q.size() to a new variable ? Can we just change from
for(int i = 0; i <levelNodeNum; i++)
tofor(int i = 0; i <q.size(); i++)
图解
解题
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res;
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while(!q.isEmpty()) {
int levelNodeNum = q.size();
List<Integer> currLevel = new ArrayList<>();
for(int i = 0; i < levelNodeNum; i++) {
TreeNode currNode = q.poll();
currLevel.add(currNode.val);
if (currNode.left != null)
q.add(currNode.left);
if (currNode.right != null)
q.add(currNode.right);
}
res.add(currLevel);
}
return res;
}
}