剑指offer-61-二叉树序列化

序列化二叉树

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

思路

  • 递归,先序遍历,把左子树用括号括起来,6!{#!}7!
    解码就是去括号

代码

import java.util.*;
public class Solution {
    String Serialize(TreeNode root) {
        if(root==null){return "#!";}
        String res=root.val+"!";
        return res+"{"+Serialize(root.left)+"}"+Serialize(root.right);
  }
    TreeNode Deserialize(String str) {
        if(str.length()<=0 || str.charAt(0)=='#'){return null;}
        int p=0;
        while(p<str.length() && str.charAt(p)!='!'){
            p++;
        }
        TreeNode root=new TreeNode(Integer.parseInt(str.substring(0,p)));
        p++;
        int start=p;//当前p为{
        int cnt=1;
        while(cnt>0){
            p++;
            if(str.charAt(p)=='}'){
                cnt--;
            }
            if(str.charAt(p)=='{'){
                cnt++;
            }
        }
        root.left=Deserialize(str.substring(start+1,p));
        root.right=Deserialize(str.substring(p+1));
       return root;
  }
}
剑指offer与数据结构 文章被收录于专栏

本专栏包括剑指offer题目和一些刷题用的数据结构,单调栈,树状数组,差分数组,后面还会更新红黑树等较为复杂的数据结构

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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