public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (root==null) return res;
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.add(root);
int currentElement=1;
while (q.size()!=0) {
int nextElement = 0;
List<Integer> currLevel = new ArrayList<Integer>();
for (int i=0; i<currentElement; i++) {
TreeNode currNode = q.poll();
currLevel.add(currNode.val);
if (currNode.left != null) {
q.add(currNode.left);
nextElement++;
}
if (currNode.right != null) {
q.add(currNode.right);
nextElement++;
}
}
currentElement = nextElement;
res.add(currLevel);
}
return res;
}
No comments:
Post a Comment