中级农民
- 积分
- 103
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2015-6-25
- 最后登录
- 1970-1-1
|
- /**
- * Definition of TreeNode:
- * public class TreeNode {
- * public int val;
- * public TreeNode left, right;
- * public TreeNode(int val) {
- * this.val = val;
- * this.left = this.right = null;
- * }
- * }
- */
- class Solution {
- /**
- * This method will be invoked first, you should design your own algorithm
- * to serialize a binary tree which denote by a root node to a string which
- * can be easily deserialized by your own "deserialize" method later.
- */
- public String serialize(TreeNode root) {
- String result = "";
- if (root == null) {
- return result += "#,";
- }
-
- result += root.val;
- result += ",";
-
- result += serialize(root.left);
- result += serialize(root.right);
-
- return result;
- }
-
- /**
- * This method will be invoked second, the argument data is what exactly
- * you serialized at method "serialize", that means the data is not given by
- * system, it's given by your own serialize method. So the format of data is
- * designed by yourself, and deserialize it here as you serialize it in
- * "serialize" method.
- */
- public TreeNode deserialize(String data) {
- // 转成字符串,好处理一些
- String[] strList = data.split(",");
- ArrayList<String> nodeList = new ArrayList<String>(strList.length);
- for (String str : strList) {
- nodeList.add(str);
- }
- TreeNode root = deserializeHelper(nodeList);
- return root;
- }
-
- private TreeNode deserializeHelper(ArrayList<String> nodeList) {
- if (nodeList == null || nodeList.size() == 0) {
- return null;
- }
- String val = nodeList.get(0);
- nodeList.remove(0);
- if (val.equals("#")) {
- return null;
- }
- TreeNode root = new TreeNode(Integer.parseInt(val));
- root.left = deserializeHelper(nodeList);
- root.right = deserializeHelper(nodeList);
- return root;
- }
- }
复制代码 我贴个lintcode的,FYI |
|