美文网首页
二叉树的序列化

二叉树的序列化

作者: Hammy | 来源:发表于2018-02-01 22:37 被阅读0次

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

    思路:
    运用前序遍历的思路进行序列化,如果遇到null用#符号代替

    代码:

    /**
     * Created by Hammy on 2018/2/1.
     */
    public class SerializeAndDeSerialize
    {
        private int index = -1;
        
        public String Serialize(TreeNode root){
            StringBuffer stringBuffer = new StringBuffer();
            if(root == null){
                stringBuffer.append("#,");
                return stringBuffer.toString();
            }
            stringBuffer.append(root.val + ",");
            stringBuffer.append(Serialize(root.left));
            stringBuffer.append(Serialize(root.right));
            
            return stringBuffer.toString();
        }
        
        public TreeNode Deserialize(String str){
            index++;
            int length = str.length();
            if(index >= length){
                return null;
            }
            String[] strings = str.split(",");
            TreeNode treeNode = null;
            if(!strings[index].equals("#")){
                treeNode = new TreeNode(Integer.valueOf(strings[index]));
                treeNode.left = Deserialize(str);
                treeNode.right = Deserialize(str);
            }
            return treeNode;
        }
        
    }
    

    相关文章

      网友评论

          本文标题:二叉树的序列化

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