Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Solution1:BFS
广度优先遍历,queue实现
Time Complexity: O(N) Space Complexity: O(n) worst缓存
Solution2:DFS with level
DFS过程中不同level的结果list 保存到 对应ArrayList<list> result[level]中
Time Complexity: O(N) Space Complexity: O(n) worst缓存
Solution1 Code:
class Solution {
//BFS 最要在Node进入queue前就进行非空判断,使得进入queue的node本身都非null
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
List<List<Integer>> result = new LinkedList<List<Integer>>();
if(root == null) return result;
queue.offer(root);
while(!queue.isEmpty()) {
int num_on_level = queue.size();
List<Integer> cur_result = new LinkedList<Integer>();
for(int i = 0; i < num_on_level; i++) {
TreeNode cur = queue.poll();
if(cur.left != null) queue.add(cur.left);
if(cur.right != null) queue.add(cur.right);
cur_result.add(cur.val);
}
result.add(cur_result);
}
return result;
}
}
Solution2 Code:
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
dfs(result, root, 0);
return result;
}
public void dfs(List<List<Integer>> result, TreeNode root, int level) {
if (root == null) return;
if (level == result.size()) {
result.add(new LinkedList<Integer>());
}
result.get(level).add(root.val);
dfs(result, root.left, level+1);
dfs(result, root.right, level+1);
}
}