剑指offer之序列化二叉树

在这里插入图片描述

int index = -1;
    String Serialize(TreeNode root) {
    
    
        if (root == null) {
    
    
            return "#";
        }
        return root.val+","+Serialize(root.left)+","+Serialize(root.right);


    }
    TreeNode Deserialize(String str) {
    
    
        String[] s = str.split(",");
        index++;
        int len = s.length;
        if (index>len) {
    
    
            return null;
        }
        TreeNode treeNode = null;
        if (!s[index].equals("#")) {
    
    
            treeNode = new TreeNode(Integer.parseInt(s[index]));
            treeNode.left = Deserialize(str);
            treeNode.right = Deserialize(str);
        }
        return treeNode;

    }

猜你喜欢

转载自blog.csdn.net/AIJXB/article/details/113767634

相关文章