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

[LC] 297. Serialize and Deserialize Binary Tree

时间:2020-02-13 09:14:46      阅读:69      评论:0      收藏:0      [点我收藏+]

标签:parse   anti   nod   col   ++   uil   offer   stringbu   app   

You may serialize the following tree:

    1
   /   2   3
     /     4   5

as "[1,2,3,null,null,4,5]"


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Codec {

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

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

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

 

[LC] 297. Serialize and Deserialize Binary Tree

标签:parse   anti   nod   col   ++   uil   offer   stringbu   app   

原文地址:https://www.cnblogs.com/xuanlu/p/12302168.html

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