题解 | #序列化二叉树#层次遍历

序列化二叉树

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;

    }

}
*/
import java.util.*;
public class Solution {
    String Serialize(TreeNode root) {
        if(root == null) return null;
        String res = "";
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        q.offer(root);
        while(!q.isEmpty()) {
            int size = q.size();
            for(int i=0;i<size;i++) {
                TreeNode node = q.poll();
                if(node == null) {
                    res += "#!";
                } else {
                    res += node.val + "!";
                    q.offer(node.left);
                    q.offer(node.right);
                }
            }
        }
        return res;
    }
    TreeNode Deserialize(String str) {
        if(str == null || str.isEmpty()) return null;
       String[] strs = str.split("!");
        if(strs == null || strs.length ==0 || strs[0] =="#") return null;
        
        TreeNode root = new TreeNode(Integer.parseInt(strs[0]));
        
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        int idx = 1;
        while(!q.isEmpty()&&idx<strs.length) {
            int size = q.size();
            for(int i =0; i<size; i++) {
                TreeNode node = q.poll();
                String l = strs[idx++];
                String r = strs[idx++];
                if(!l.equals("#")) {
                    TreeNode ln = new TreeNode(Integer.parseInt(l));
                    q.offer(ln);
                    node.left = ln;
                }
                if(!r.equals("#")) {
                    TreeNode rn = new TreeNode(Integer.parseInt(r));
                    q.offer(rn);
                    node.right = rn;
                }
                
            }
        }
        return root;
    }
}
全部评论

相关推荐

11-14 16:09
门头沟学院 Java
Java抽象带篮子:可以看看我的苍穹外卖话术帖子和八股笔记帖子
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务