kouchworm
BAN USERprivate final static String P_LEFT = "{", P_RIGHT="}", SEPARATOR=";";
public String serialize(Node tree){
StringBuilder sb = new StringBuilder();
if(tree != null){
if(tree.value != null){
sb.append(P_LEFT).append(tree.value);
List<Node> children = tree.children;//in width traverse
if(children != null && children.size()>0){
sb.append(SEPARATOR+P_LEFT);
for (Node node : children) {
sb.append(serialize(node));//recursive
sb.append(SEPARATOR);
}
sb.append(P_RIGHT);
}
sb.append(P_RIGHT);
}
}
return sb.toString();
}
public Node deSerialize(String srcStr){
Node tree = null;
if((srcStr != null) && (srcStr.length() >= 2)){
srcStr = srcStr.substring(1, srcStr.length()-1);//strip {}
tree = new Node();
//get value
int firstSeparatorIndx = srcStr.indexOf(SEPARATOR);
if(firstSeparatorIndx >0){
String val = srcStr.substring(0, firstSeparatorIndx);
tree.value = val;
//get children
String childrenStr = srcStr.substring(firstSeparatorIndx+2, srcStr.length()-1);
String[] childrenSrcStrs = childrenStr.split(SEPARATOR);
List<Node> childrenNodes = new ArrayList<Node>();
for (String string : childrenSrcStrs) {
Node child = deSerialize(string);
if(child != null){
childrenNodes.add(child);//recursive
}
}
tree.children = childrenNodes;
}else{
tree.value = srcStr;
}
}
return tree;
}
public static class Node{
String value;
List<Node> children;
}
after read sandeep's generic implementation, add a else{} to above square solution.
...
double pow = root * root;
if(pow > val){
end = root;
}else if(pow < val){
start = root;
}else{//this branch should be caught, otherwise you cannot get "exact" root, like findSquareRoot(2), you cannot get 2 as result
System.out.println(root+" ("+start+","+end+")");
return root;
}
Any one interested this Java in-place solution, less lines
- kouchworm July 20, 2014