//time: O(n), space: O(n).
public ArrayList<String> serialize(Node root) {
ArrayList<String> result = new ArrayList<String>();
help(root, result);
return result;
}
public void help(TreeNode root, ArrayList<Integer> result) {
if(root == null) {
result.add("#");
return;
}else {
result.add(String.parseInt(root.val));
help(root.left, result);
help(root.right, result);
}
}
public Node deserialize(ArrayList<String> result) {
Pair pair = help(result, 0);
return pair.node;
}
public Pair help(ArrayList<String> result, int index) {
String s = result.get(index);
if(s == "#") return new Pair(null, index + 1);
Node node = new Node(Integer.parseInt(s));
Pair pLeft = help(result, index + 1);
node.left = pLeft.node;
Pair pRight = help(result, pLeft.index);
node.right = pRight.node;
return new Pair(node, pRight.index);
}
class Pair {
Node node;
int index;
public Pair(Node node, int index) {
this.node = node;
this.index = index;
}
}
class Node {
Node left;
Node right;
Node val;
public Node(int val) {
this.val = val;
}
}
Serialize and deserialize a binary tree
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.