Below is my code:
class Node{
int value;
Node left;
Node right;
Node parent;
//getters, setters
}
Create the Tree
private static void createTree() throws FileNotFoundException{
Map<String,Node> nodeMap = new HashMap<String,Node>();
Scanner sc = new Scanner(new File("<location>"));
int row =0;
while(sc.hasNextLine()){
String line = sc.nextLine();
Scanner scanLine = new Scanner(line);
System.out.println(line);
int col =0;
while(scanLine.hasNextInt()){
int value = scanLine.nextInt();
System.out.println(row+","+col+"="+value);
Node node = new Node(value);
nodeMap.put(row+","+col,node);
if(row >0){
if(col %2 ==0){
//left node
Node parent = nodeMap.get(row-1+","+col/2);
if(parent !=null){
node.setParent(parent);
parent.setLeft(node);
}
}else{
//right node
Node parent = nodeMap.get(row-1+","+(col-1)/2);
if(parent !=null){
node.setParent(parent);
parent.setRight(node);
}
}
}
col++;
}
row++;
}
System.out.println(nodeMap);
Node root = nodeMap.get("0,0");
traverseTree(root);
System.out.println("sum="+sum);
}
Actual Traversal
static int sum =0;
private static void traverseTree(Node n){
if(n != null){
sum+=n.value;
traverseTree(n.left);
traverseTree(n.right);
}
}
I have 2 questions:
-
Read the input and create the tree: I read it from a file and store
the root node in the hashmap. What are the alternatives? -
In the recursive search, I am keeping the sum outside the function, so its possible to calculate the sum in a sequential fashion. Is it possible to keep the sum variable inside and return the total value at the end?
How you are doing it seems pretty reasonable given the apparent input format, however I’d recommend using a
List<List<Node>>rather than storing it with strings, as your performance may degrade fairly quickly because the strings are very similar, which may cause hash collisions, degrading your map’s performance greatly if the input is large.