原题链接在这里:
题目:
Given a binary tree, return the level order traversal 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]]
题解:
是一道BFS,利用queue,先进先出,并利用curCount来判断是否走完了当前一层。当curCount = 0 时表示当前一层走完,要把当前list加入res里,再刷新list,问题是不要忘记同时刷新curCount和nextCount.
Time Complexity: O(n). Space: O(n).
AC Java:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public List
> levelOrder(TreeNode root) { List
> res = new ArrayList
>(); if(root == null){ return res; } LinkedList que = new LinkedList (); que.add(root); int curCount = 1; int nextCount = 0; List item = new ArrayList (); while(!que.isEmpty()){ TreeNode tn = que.poll(); item.add(tn.val); curCount--; if(tn.left != null){ que.add(tn.left); nextCount++; } if(tn.right != null){ que.add(tn.right); nextCount++; } if(curCount == 0){ res.add(new ArrayList (item)); item = new ArrayList (); curCount = nextCount; nextCount = 0; } } return res; }}
类似的有, , , , , .