码迷,mamicode.com
首页 > 其他好文 > 详细

297. Serialize and Deserialize Binary Tree

时间:2016-07-03 11:38:26      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

/*
 * 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

标签:

原文地址:http://www.cnblogs.com/zmyvszk/p/5636927.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!