Leetcode 449. Serialize and Deserialize BST

14 篇文章 0 订阅
public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        // If tree is empty just return a null string
        if (root == null)
            return "";
            
        // BFS, saving nodes in the BST level by level
        StringBuilder sb = new StringBuilder();
        Queue<TreeNode> queue = new LinkedList<>();
        sb.append(root.val + " ");
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode curr = queue.poll();
            if (curr.left != null) {
                queue.offer(curr.left);
                sb.append(curr.left.val + " ");
            }
            else
                sb.append("null" + " ");
            if (curr.right != null) {
                queue.offer(curr.right);
                sb.append(curr.right.val + " ");
            } else 
            sb.append("null" + " ");
        }
        
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        // null tree when data length is 0
        if (data.length() == 0)
            return null;
            
        // BFS, restore BST level by level
        String[] dataArr = data.split(" ");                             // split the data by whitespace
        TreeNode root = new TreeNode(Integer.parseInt(dataArr[0]));     // first element in the dataArr is the root
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);                                              // put the root node into the queue
        int i = 1;                                                      // a cursor to indicate which element in teh array should enqueue
        while (!queue.isEmpty()) {
            int size = queue.size();            // restore the tree level by level, we need a variable to save the size of current level
            for (int k=0; k<size; k++) {
                TreeNode curr = queue.poll();
                // Restore left child
                if (dataArr[i].equals("null")) {
                    curr.left = null;
                } else {
                    curr.left = new TreeNode(Integer.parseInt(dataArr[i]));
                    queue.offer(curr.left);
                }
                i++;
                // Restore right child 
                if (dataArr[i].equals("null")) {
                    curr.right = null;
                } else {
                    curr.right = new TreeNode(Integer.parseInt(dataArr[i]));
                    queue.offer(curr.right);
                }
                i++;
            }
        }
        
        return root;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值