leetcode 297. Serialize and Deserialize Binary Tree

可以用bfs,先序中序后序4种解法

我觉得bfs比较好写,所以就用了bfs

public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if(root == null)
            return "";
        StringBuilder str = new StringBuilder();
        
        Queue<TreeNode> q = new LinkedList<>();
        
        q.offer(root);
        while(!q.isEmpty()){
                TreeNode cur = q.poll();
                if(cur != null){
                    q.offer(cur.left);
                    q.offer(cur.right);
                    str.append(cur.val + " ");
                }else{
                    str.append("null ");
                }
        }
        return str.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if(data == "")
            return null;
        String[] str = data.split(" ");
        Queue<TreeNode> q = new LinkedList<>();
        
        TreeNode cur = new TreeNode(Integer.parseInt(str[0]));
        q.offer(cur);
        
        for(int i=1; i<str.length; i++){
            TreeNode parent = q.poll();
            if(!str[i].equals("null")){
                TreeNode left = new TreeNode(Integer.parseInt(str[i]));
                parent.left = left;
                q.offer(left);
            }
            
            if(!str[++i].equals("null")){
                TreeNode right = new TreeNode(Integer.parseInt(str[i]));
                parent.right = right;
                q.offer(right);
            }
        }
        return cur;
        
    }
}

 

posted @ 2019-08-19 01:42  南山南北秋悲  阅读(152)  评论(0编辑  收藏  举报