美文网首页
序列化二叉树

序列化二叉树

作者: 稀饭粥95 | 来源:发表于2018-08-30 00:24 被阅读6次

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

    public class Solution {
        int index=-1;
        public String Serialize(TreeNode root) {
            StringBuilder strb = new StringBuilder();
            if(root==null){
                strb.append("#,");
                return strb.toString();
            }
            strb.append(root.val);
            strb.append(",");
            strb.append(Serialize(root.left));
            strb.append(Serialize(root.right));
            return strb.toString();
            
        }
    
        public TreeNode Deserialize(String str) {
            index++;
            String stra[] = str.split(",");
            TreeNode node = null;
            if(!stra[index].equals("#")){
                node = new TreeNode(Integer.valueOf(stra[index]));
                node.left = Deserialize(str);
                node.right=Deserialize(str);
            }
            return node;
        }
    }
    

    相关文章

      网友评论

          本文标题:序列化二叉树

          本文链接:https://www.haomeiwen.com/subject/dbvlwftx.html