Skip to content

Instantly share code, notes, and snippets.

@Eternity-Yarr
Created March 5, 2014 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Eternity-Yarr/9368088 to your computer and use it in GitHub Desktop.
Save Eternity-Yarr/9368088 to your computer and use it in GitHub Desktop.
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class Tree
{
public class Node
{
public List<Node> childList = new LinkedList<>();
public List<Integer> numberList = new LinkedList<>();
Node(LinkedList<String> l)
{
exitWhile:
while (!l.isEmpty())
{
String s = l.pop();
switch (s)
{
case "[":
Node n = new Node(l);
childList.add(n);
break;
case "]": break exitWhile;
default : numberList.add(Integer.parseInt(s));break;
}
}
}
public int nodeSum()
{
int s = 0;
for (Integer i: numberList){s += i;}
System.out.println(s);
return s;
}
public int sum()
{
int s = 0;
if (!childList.isEmpty()){for (Node x: childList){s += x.sum();}}
s += nodeSum();
return s;
}
}
Tree (String[] treeStr)
{
LinkedList<String> l = new LinkedList<>(Arrays.asList(treeStr));
Node n = new Node(l);
System.out.println("Total sum:"+n.sum());
}
public static void main(String[] args)
{
String[] treeStr = {"[","1","[","2","3","]","4","[","5","[","6","7","]","]","[","8","]","]"};
Tree t = new Tree(treeStr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment