U家面试prepare: Serialize and Deserialize Tree With Uncertain Children Nodes

Like Leetcode 297, Serialize and Deserialize Binary Tree, the only difference, this is not a binary tree.

The method to serialize is like this: (1(2)(3(5)(6))(4(7)))

if '(', right shift 1 position to the start of the number, use while loop to find the end of the number(either end with'(' or ')'), create a treeNode use this number as value, here we have two cases:

1. if stack is empty, this treeNode is root. push this node to stack

2. not empty, then this node is one child of stack.peek(), add this node to stack.peek().children, push this node to stack

else if ')', pop

 package uber;

 import java.util.ArrayList;
import java.util.List;
import java.util.Stack; public class SeDeTree {
public class TreeNode {
int val;
List<TreeNode> children;
public TreeNode (int num) {
this.val = num;
this.children = new ArrayList<TreeNode>();
}
} TreeNode deserialize(String input) {
if (input==null || input.length()==0) return null;
char[] in = input.toCharArray();
TreeNode root = new TreeNode(0); //initialize
Stack<TreeNode> stack = new Stack<TreeNode>();
int pos = 0; while (pos < input.length()) {
if (in[pos] == '(') {
pos++;
int number = 0; // each treenode val
while (pos<input.length() && Character.isDigit(in[pos])) {
number = number*10 + (int)(in[pos] - '0');
pos++;
}
TreeNode cur = new TreeNode(number);
if (stack.isEmpty()) {
root = cur;
}
else {
stack.peek().children.add(cur);
}
stack.push(cur);
}
else if (in[pos] == ')') {
stack.pop();
pos++;
}
}
return root;
} String serialize(TreeNode cur) {
if (cur == null) return "";
StringBuilder res = new StringBuilder();
res.append('(');
res.append(cur.val);
for (TreeNode child : cur.children) {
String str = serialize(child);
res.append(str);
}
res.append(')');
return res.toString();
} /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SeDeTree sol = new SeDeTree();
//String in = "(1(2)(3(5)(6))(4(7)))";
String in = "(10(2(3)(4))(5)(6))";
TreeNode root = sol.deserialize(in);
System.out.println(root.val);
String output = sol.serialize(root);
System.out.println(output);
} }
上一篇:GJM: 设计模式 - 模板方法模式(Template Method)


下一篇:【转载】Apache shutdown unexpectedly启动错误解决方法