|
| 1 | +importjava.util.ArrayList; |
| 2 | +importjava.util.Arrays; |
| 3 | +importjava.util.List; |
| 4 | + |
| 5 | +/* |
| 6 | + * @lc app=leetcode.cn id=297 lang=java |
| 7 | + * |
| 8 | + * [297] 二叉树的序列化与反序列化 |
| 9 | + */ |
| 10 | + |
| 11 | +// @lc code=start |
| 12 | +/** |
| 13 | + * Definition for a binary tree node. |
| 14 | + * public class TreeNode { |
| 15 | + * int val; |
| 16 | + * TreeNode left; |
| 17 | + * TreeNode right; |
| 18 | + * TreeNode(int x) { val = x; } |
| 19 | + * } |
| 20 | + */ |
| 21 | +classCodec { |
| 22 | + |
| 23 | +// Encodes a tree to a single string. |
| 24 | +publicStringserialize(TreeNoderoot) { |
| 25 | +if (root ==null) |
| 26 | +return"#"; |
| 27 | +returnroot.val +"," +serialize(root.left) +"," +serialize(root.right); |
| 28 | + } |
| 29 | + |
| 30 | +// Decodes your encoded data to tree. |
| 31 | +publicTreeNodedeserialize(Stringdata) { |
| 32 | +String[]datas =data.split(","); |
| 33 | +ArrayList<String>nodes =newArrayList<String>(Arrays.asList(datas)); |
| 34 | +returndeserialize(nodes); |
| 35 | + } |
| 36 | + |
| 37 | +privateTreeNodedeserialize(List<String>nodes) { |
| 38 | +if (nodes.isEmpty()) |
| 39 | +returnnull; |
| 40 | +Stringval =nodes.remove(0); |
| 41 | +if (val.equals("#")) |
| 42 | +returnnull; |
| 43 | +TreeNoderoot =newTreeNode(Integer.parseInt(val)); |
| 44 | +root.left =deserialize(nodes); |
| 45 | +root.right =deserialize(nodes); |
| 46 | +returnroot; |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +// Your Codec object will be instantiated and called as such: |
| 51 | +// Codec ser = new Codec(); |
| 52 | +// Codec deser = new Codec(); |
| 53 | +// TreeNode ans = deser.deserialize(ser.serialize(root)); |
| 54 | +// @lc code=end |