59、序列化二叉树

一、题目

请实现两个函数,分别用来序列化和反序列化二叉树

二、解法

 1 /*
 2 public class TreeNode {
 3     int val = 0;
 4     TreeNode left = null;
 5     TreeNode right = null;
 6 
 7     public TreeNode(int val) {
 8         this.val = val;
 9 
10     }
11 
12 }
13 */
14 public class Solution {
15     public int index = -1;
16      String Serialize(TreeNode root) {
17             StringBuffer sb = new StringBuffer();
18             if(root == null){
19                 sb.append("#,");
20                 return sb.toString();
21             }
22             sb.append(root.val + ",");
23             sb.append(Serialize(root.left));
24             sb.append(Serialize(root.right));
25             return sb.toString();
26                 
27      }
28      TreeNode Deserialize(String str) {
29            index++;
30            int len = str.length();
31            if(index >= len)
32                return null;
33            String[] strr = str.split(",");
34            TreeNode node = null;
35            if(!strr[index].equals("#")){
36                node = new TreeNode(Integer.valueOf(strr[index]));
37                node.left = Deserialize(str);
38                node.right = Deserialize(str);
39            }
40            return node;
41      }
42 }

 

posted @ 2017-09-01 10:53  fankongkong  阅读(164)  评论(0编辑  收藏  举报