Last active
August 29, 2015 13:56
-
-
Save mmagm/9216629 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Stack; | |
import java.util.Queue; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.ArrayDeque; | |
import java.util.LinkedList; | |
public class Tree { | |
private Node root = null; | |
public class Node { | |
public List<Node> childList; | |
public List<Integer> numberList; | |
public Node() { | |
this.childList = new ArrayList<Node>(); | |
this.numberList = new ArrayList<Integer>(); | |
} | |
} | |
public class ExpressionException extends Exception { | |
public ExpressionException(String message) { | |
super(message); | |
} | |
} | |
public Tree(String[] treeStr) throws Tree.ExpressionException { | |
root = buildTree(treeStr); | |
} | |
public void printSums() { | |
Queue<Node> queue = new LinkedList<Node>(); | |
queue.add(root); | |
while (!queue.isEmpty()) { | |
Node node = queue.remove(); | |
int sum = 0; | |
for(Integer i : node.numberList) | |
sum += i; | |
System.out.println(sum); | |
for (Node subNode : node.childList) | |
queue.add(subNode); | |
} | |
} | |
private Node buildTree(String[] treeStr) throws Tree.ExpressionException { | |
Stack<Node> stack = new Stack<Node>(); | |
Node root = null; | |
for (int i = 0; i < treeStr.length; i++) { | |
if (treeStr[i].equals("[")) { | |
Node node = new Node(); | |
if (!stack.isEmpty()) { | |
Node parent = stack.peek(); | |
parent.childList.add(node); | |
} | |
stack.push(node); | |
} else if (treeStr[i].equals("]")) { | |
if (stack.isEmpty()) | |
throw new Tree.ExpressionException("wrong parentheses"); | |
root = stack.pop(); | |
} else if (Character.isDigit(treeStr[i].charAt(0))) { | |
Node node = stack.peek(); | |
node.numberList.add(Integer.parseInt(treeStr[i])); | |
} | |
} | |
if (!stack.isEmpty()) | |
throw new Tree.ExpressionException("wrong parentheses"); | |
return root; | |
} | |
public static void main(String[] args) throws Tree.ExpressionException { | |
String[] treeStr = { "[","1","[","2","3","]","4","[","5","[","6","7","]","]","[","8","]","]" }; | |
Tree tree = new Tree(treeStr); | |
tree.printSums(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment