题解 | #序列化二叉树#

序列化二叉树

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

import java.util.Queue;
import java.util.LinkedList;
/*
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) {
        StringBuffer sb = new StringBuffer();
        Queue<TreeNode>q = new LinkedList<TreeNode>();
        q.offer(root); 
        while(!q.isEmpty()){
            TreeNode t = q.poll();
            if(t!=null){
                sb.appe***al);
                sb.append(",");
                q.offer(t.left); 
                q.offer(t.right); 
            }
            else{
                sb.append("#");
                sb.append(",");
            }
        }
        return sb.toString();
    }
    TreeNode Deserialize(String str) {
        String[] s = str.split(",");
        if(s[0].equals("#")) return null;
        int i = 0;
        Queue<TreeNode>q = new LinkedList<TreeNode>();
        TreeNode root = new TreeNode(Integer.parseInt(s[i]));
        i++;
        q.offer(root);
        while(!q.isEmpty() && i<s.length){
            TreeNode t = q.poll();
            if(s[i].equals("#"))
                t.left = null;
            else{
                TreeNode k = new TreeNode(Integer.parseInt(s[i]));
                t.left = k;
                q.offer(k);
            }
            i++;
            
            if(s[i].equals("#"))
                t.right = null;
            else{
                TreeNode k = new TreeNode(Integer.parseInt(s[i]));
                t.right = k;
                q.offer(k);
            }
            i++;
        }
        return root;
    }
}

String 转int String转string数组

全部评论

相关推荐

11-15 17:19
湖南大学 Java
成果成果成果果:这是哪个公司的hr,这么离谱吗,我没见过用性别卡技术岗的,身边女性同学拿大厂offer的比比皆是
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务