题解 | #序列化二叉树#

序列化二叉树

http://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    // 根据前序遍历获取二叉树!
    String Serialize(TreeNode root) {
        if(root == null) return "#";
        StringBuilder sub = new StringBuilder();
        sub.append(root.val);
        sub.append('!');
        sub.append(Serialize(root.left));
        sub.append(Serialize(root.right));
        return sub.toString();
    }
    
    int index = 0; 
    TreeNode Deserialize(String str) {
        if(index >= str.length()) return null;
        if(str.charAt(index) == '#') { index++; return null;}
        int val = 0;
        while(index < str.length() && str.charAt(index) != '!'){
            val = val*10 + str.charAt(index)-'0';
            index++;
        } 
        TreeNode root = new TreeNode(val);
        index++;
        root.left = Deserialize(str);
        root.right = Deserialize(str);
        return root;
    }
}
全部评论

相关推荐

10-29 18:20
济南大学 Java
用微笑面对困难:他不是人事吗,怎么净特么不干人事
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务