Here's a sample solution for "Populating Next Right Pointers in Each Node" puzzle:
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
public void connect(Node root) {
HashMap<Integer,List<Node>> map = new HashMap<Integer,List<Node>>();
traverse(root, map , 0);
}
private void traverse(Node root, HashMap<Integer,List<Node>> map , int level){
if(root != null){
if(map.containsKey(level)){
List<Node> temp = map.get(level);
Node set = temp.get(temp.size() -1 );
set.next = root;
root.next = null;
temp.add(root);
map.put(level,temp);
}
else{
root.next = null;
List<Node> temp = new ArrayList<Node>();
temp.add(root);
map.put(level,temp);
}
level++;
traverse(root.left, map , level);
traverse(root.right, map,level);
System.out.println("test");
}
}
The solution itself doesn't really matter, but what I'm struggling with is determining its Space complexity:
Logically the type of object we are storing in a HashMap should make a difference on its Space complexity, but how we can determine it by having the key and value of the map?
In other words, if we are storing just 5 keys (for 5 nodes) in this map, can we conclude that the space complexity of HashMap<Integer,List<Node>> map = new HashMap<Integer,List<Node>>();
is just O(n)
or since the value of those keys are a List
is should be more than that?