297. Serialize and Deserialize Binary Tree

Posted 我的名字叫周周

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了297. Serialize and Deserialize Binary Tree相关的知识,希望对你有一定的参考价值。

/*
 * 297. Serialize and Deserialize Binary Tree 
 * 2016-3-27 by Mingyang
 * 还是自己的思路更清晰一点
 * 就是BFS,用一个queue来装,不过这里就算null也要装起来占位
 * 以便以后的更为方便的deserialize
 */
class Codec {
    public String serialize(TreeNode root) {
        if (root == null) return "";
        Queue<TreeNode> q = new LinkedList<>();
        StringBuilder res = new StringBuilder();
        q.add(root);
        while (!q.isEmpty()) {
            TreeNode node = q.poll();
            if (node == null) {
                res.append("n ");
                continue;
            }
            res.append(node.val + " ");
            q.add(node.left);
            q.add(node.right);
        }
        return res.toString();
    }
    public TreeNode deserialize(String data) {
        if (data == "") return null;
        Queue<TreeNode> q = new LinkedList<>();
        String[] values = data.split(" ");
        TreeNode root = new TreeNode(Integer.parseInt(values[0]));
        q.add(root);
        //这里不用queue来遍历,直接用array遍历
        //不用判断等于n的情况,因为这种情况会被自动跳过
        for (int i = 1; i < values.length; i++) {
            TreeNode parent = q.poll();
            if (!values[i].equals("n")) {
                TreeNode left = new TreeNode(Integer.parseInt(values[i]));
                parent.left = left;
                q.add(left);
            }
            if (!values[++i].equals("n")) {
                TreeNode right = new TreeNode(Integer.parseInt(values[i]));
                parent.right = right;
                q.add(right);
            }
        }
        return root;
    }
}

 

以上是关于297. Serialize and Deserialize Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章

297. Serialize and Deserialize Binary Tree

297. Serialize and Deserialize Binary Tree

297. Serialize and Deserialize Binary Tree

297. Serialize and Deserialize Binary Tree

297.Serialize and Deserialize Binary Tree

297. Serialize and Deserialize Binary Tree