It is same with problem 297


  • 0
    F

    bst is a special case of binary tree, so just copy the code of problem 297 directly

        public String serialize(TreeNode root) {
            StringBuilder stringBuilder = new StringBuilder();
            preOrder(root, stringBuilder);
            return stringBuilder.toString().trim();
        }
    
        public TreeNode deserialize(String data) {
            if (data == null || data.isEmpty()) {
                return null;
            }
            LinkedList<String> linkedList = new LinkedList<>(Arrays.asList(data.split(" ")));
            return deserialize(linkedList);
        }
    
        private void preOrder(TreeNode root, StringBuilder stringBuilder) {
            if (root == null) {
                stringBuilder.append("null").append(" ");
            } else {
                stringBuilder.append(root.val).append(" ");
                preOrder(root.left, stringBuilder);
                preOrder(root.right, stringBuilder);
            }
        }
    
        private TreeNode deserialize(LinkedList<String> linkedList) {
            String first = linkedList.pollFirst();
            if (first.equals("null")) {
                return null;
            }
            TreeNode treeNode = new TreeNode(Integer.parseInt(first));
            treeNode.left = deserialize(linkedList);
            treeNode.right = deserialize(linkedList);
            return treeNode;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.